<template>
  <div>
    <!-- <input type="file" @input="handleInput"/> -->
    <div v-if="showbranchFilter">
      <p class="text-2xl font-bold mb-5">网点管理</p>
      <div>
        <header-select
          ref="headerSelect"
          :setFooList="setFooList"
          :fooList="fooList"
          :level="level"
          :role="role"
        />
      </div>
      <div class="mt-4">
        <!-- 搜索框 -->
        <!-- <a-input
          :disabled="cascaderValue.length == 0 ? false : true"
          placeholder="通过输入详细地址搜索"
          v-model="addressSearchValue"
          style="width: 20%; margin-right: 15px"
        /> -->
        <!-- 操作 -->
        <a-button type="primary" style="margin-right: 10px" @click="clickQuery"
          >查询</a-button
        >
        <a-button type="primary" style="margin-right: 10px" @click="clickReset"
          >重置</a-button
        >
        <a-button
          v-if="hasOperateAuth"
          type="primary"
          style="margin-right: 10px"
          @click="clickAddOutlet"
          >新增</a-button
        >
      </div>
    </div>
    <div v-else>
      <!-- <div class="flex items-center">
        <a-range-picker
          @change="onRangePickerChange"
          :value="rangePickerValue"
        />
        <a-input
          class="w-40 ml-5"
          placeholder="姓名模糊搜索"
          v-model="searchPageReqParams.name"
        />
        <a-input
          class="w-40 ml-5"
          placeholder="手机号模糊搜索"
          v-model="searchPageReqParams.phone"
        />
        <a-button class="ml-5" type="primary" @click="clickQueryOnSearchPage"
          >查询</a-button
        >
        <a-button class="ml-5" type="primary" @click="clickResetOnSearchPage"
          >重置</a-button
        >
        <a-button class="ml-5" type="primary" @click="clickAddNewOnSearchPage"
          >新增</a-button
        >
      </div> -->
      <div>
        <a-table
          rowKey="id"
          :columns="outletColumns"
          :loading="tableLoading"
          bordered
          class="mt-5"
          :dataSource="dataSource"
        >
          <template #note="text, record">
            <a
              v-if="!record.is_normal_work"
              href="#"
              @click="clickViewNote(record)"
              >查看</a
            >
          </template>
          <template #opening_hours="text, record">
            {{ record.weekend_status | filterWorkDay }}
            {{ text }}
          </template>
          <template #is_normal_work="text">
            {{ text === true ? "是" : "否" }}
          </template>
          <template #operate="text, record">
            <a href="javascript:;" @click="clickEdit(record)">编辑</a>
            <a
              v-if="hasDeleteAuth"
              href="javascript:;"
              @click="clickDelete(record)"
              ><a-divider type="vertical" />删除</a
            >
          </template>
        </a-table>
      </div>
    </div>
    <a-modal
      title="查看"
      v-model="showNote"
      :footer="null"
      style="width: 800px"
    >
      <spin :spinning="showNoteLoading">
        {{ noteContent }}
      </spin>
      <div class="h-5"></div>
    </a-modal>
    <a-modal
      v-model="visible"
      :footer="null"
      :afterClose="afterClose"
      width="900px"
    >
      <div
        class="text-center text-lg font-semibold"
        v-if="modalType === eModalType.edit"
      >
        编辑网点
      </div>
      <div
        class="text-center text-lg font-semibold"
        v-else-if="modalType === eModalType.create"
      >
        新增网点
      </div>
      <!-- 创建网点创建网点创建网点创建网点创建网点创建网点创建网点创建网点创建网点创建网点创建网点创建网点 -->
      <FormModel
        :model="formData"
        :rules="createOutlet_formRules"
        v-if="modalType === eModalType.create"
        layout="horizontal"
        ref="createOutlet_form"
        style="position: relative; left: 12rem"
      >
        <HeaderSelect3
          ref="headerselect3"
          :fooList="fooList_createOutlet"
          :setFooList="setFooList_createOutlet"
          :level="0"
          :userLevel="0"
        />
        <FormModelItem
          class="base_form_item my-2"
          :label="'所属二级支行'"
          prop="secondSubBranch"
        >
          <a-input
            v-model="formData.secondSubBranch"
            :placeholder="'请输入二级支行名称'"
          />
        </FormModelItem>
        <FormModelItem
          class="base_form_item my-2 ml-7"
          :label="'详细地址'"
          prop="location"
        >
          <a-input
            v-model="formData.location"
            :placeholder="'请输入详细地址'"
          />
        </FormModelItem>
        <FormModelItem
          class="base_form_item my-2 ml-10"
          label="是否营业"
          style="position: relative"
        >
          <a-switch
            default-checked
            v-model="formData.isOpen"
            checked-children="是"
            un-checked-children="否"
          />
        </FormModelItem>
        <div class="flex" style="position: relative; left: 1.75rem">
          <FormModelItem
            class="base_form_item my-2 mr-2 ml-4"
            label="经纬度"
            prop="lo"
          >
            <a-input class="w-32" placeholder="经度" v-model="formData.lo" />
          </FormModelItem>
          <FormModelItem class="base_form_item my-2" prop="la">
            <a-input
              class="w-32 mr-2"
              placeholder="纬度"
              v-model="formData.la"
            />
            <a-button type="primary" @click="getLalo">自动获取</a-button>
          </FormModelItem>
        </div>
        <div class="flex" style="position: relative; left: -12rem">
          <div class="flex">
            <FormModelItem class="base_form_item my-2" label="营业时间">
              <CheckBoxGroup v-model="formData.openDays">
                <Checkbox
                  v-for="item in openDaysOptions"
                  :disabled="item.disabled"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.label }}</Checkbox
                >
              </CheckBoxGroup>
              <div class="flex">
                <FormModelItem
                  prop="startTime"
                  class="flex justify-center mr-2"
                >
                  <TimePicker
                    v-model="formData.startTime"
                    format="HH:mm"
                    placeholder="开始时间"
                    :allowClear="false"
                    :disabledHours="getDisabledHours1"
                    :disabledMinutes="getDisabledMinutes1"
                  ></TimePicker>
                </FormModelItem>
                <FormModelItem prop="endTime" class="flex justify-center">
                  <TimePicker
                    v-model="formData.endTime"
                    format="HH:mm"
                    placeholder="结束时间"
                    :allowClear="false"
                    :disabledHours="getDisabledHours"
                    :disabledMinutes="getDisabledMinutes"
                  ></TimePicker>
                </FormModelItem>
              </div>
            </FormModelItem>
          </div>
          <FormModelItem class="base_form_item my-2" label="备注" prop="remark">
            <TextArea
              placeholder="请输入备注"
              max="50"
              maxlength="15"
              v-model="formData.remark"
            ></TextArea>
          </FormModelItem>
        </div>
        <div
          class="flex items-center justify-center"
          style="position: relative; left: -12rem"
        >
          <a-button @click="handleClickCancel">取消</a-button>
          <a-button type="primary" class="ml-10" @click="handleClickConfirm"
            >确认</a-button
          >
        </div>
      </FormModel>
      <!--  编辑网点编辑网点编辑网点编辑网点编辑网点编辑网点编辑网点编辑网点编辑网点编辑网点编辑网点编辑网点编辑网点编辑网点编辑网点编辑网点编辑网点 -->
      <FormModel
        v-if="modalType === eModalType.edit"
        :model="formData"
        :rules="formRules"
        layout="horizontal"
        ref="form"
        style="position: relative; left: 12rem"
      >
        <FormModelItem
          class="base_form_item my-2"
          label="所属一级分行"
          v-if="modalType === eModalType.edit"
        >
          <Select
            :disabled="modalType === eModalType.edit"
            :value="formData.firstBranch"
            @change="handleFirstBanchChange"
            placeholder="请选择所属一级分行"
          >
            <SelectOption
              v-for="item in firstBranchOptions"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</SelectOption
            >
          </Select>
        </FormModelItem>
        <FormModelItem
          class="base_form_item my-2"
          label="所属二级分行"
          v-if="modalType === eModalType.edit"
        >
          <Select
            :value="formData.secondBranch"
            :disabled="modalType === eModalType.edit"
            @change="handleSecondBanchChange"
            placeholder="请选择所所属二级分行"
          >
            <SelectOption
              v-for="item in secondBranchOptions"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</SelectOption
            >
          </Select>
        </FormModelItem>
        <FormModelItem
          class="base_form_item my-2"
          label="所属一级支行"
          v-if="modalType === eModalType.edit"
        >
          <Select
            :disabled="modalType === eModalType.edit"
            :value="formData.firstSubBranch"
            @change="handleFirstSubBanchChange"
            placeholder="请选择所属一级支行"
          >
            <SelectOption
              v-for="item in firstSubBranchOptions"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</SelectOption
            >
          </Select>
        </FormModelItem>
        <FormModelItem
          class="base_form_item my-2"
          label="原属二级支行"
          v-if="modalType === eModalType.edit"
        >
          <Select
            :disabled="modalType === eModalType.edit"
            :value="formData.secondSubBranch"
            @change="handleSecondSubBanchChange"
            placeholder="请选择所属二级支行"
          >
            <SelectOption
              v-for="item in secondSubBranchOptions"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</SelectOption
            >
          </Select>
        </FormModelItem>
        <FormModelItem
          class="base_form_item my-2"
          label="现属二级支行"
          prop="newSecondSubBranch"
          v-if="modalType === eModalType.edit"
          style="position: relative; left: -0.75rem"
        >
          <a-input
            v-model="formData.newSecondSubBranch"
            placeholder="请输入现属二级支行名称"
          />
        </FormModelItem>
        <FormModelItem
          class="base_form_item my-2"
          :label="modalType === eModalType.edit ? '现详细地址' : '详细地址'"
          prop="location"
        >
          <a-input
            v-model="formData.location"
            :placeholder="
              modalType === eModalType.edit
                ? '请输入现详细地址'
                : '请输入详细地址'
            "
          />
        </FormModelItem>
        <FormModelItem
          class="base_form_item my-2"
          label="是否营业"
          style="position: relative; left: 1.5rem"
        >
          <a-switch
            default-checked
            v-model="formData.isOpen"
            checked-children="是"
            un-checked-children="否"
          />
        </FormModelItem>
        <div class="flex" style="position: relative; left: 1.75rem">
          <FormModelItem
            class="base_form_item my-2 mr-2"
            label="经纬度"
            prop="lo"
          >
            <a-input class="w-32" placeholder="经度" v-model="formData.lo" />
          </FormModelItem>
          <FormModelItem class="base_form_item my-2" prop="la">
            <a-input
              class="w-32 mr-2"
              placeholder="纬度"
              v-model="formData.la"
            />
            <a-button type="primary" @click="getLalo">自动获取</a-button>
          </FormModelItem>
        </div>
        <div class="flex" style="position: relative; left: -12rem">
          <div class="flex">
            <FormModelItem class="base_form_item my-2" label="营业时间">
              <CheckBoxGroup v-model="formData.openDays">
                <Checkbox
                  v-for="item in openDaysOptions"
                  :disabled="item.disabled"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.label }}</Checkbox
                >
              </CheckBoxGroup>
              <div class="flex">
                <FormModelItem
                  prop="startTime"
                  class="flex justify-center mr-2"
                >
                  <TimePicker
                    v-model="formData.startTime"
                    format="HH:mm"
                    placeholder="开始时间"
                    :allowClear="false"
                    :disabledHours="getDisabledHours1"
                    :disabledMinutes="getDisabledMinutes1"
                  ></TimePicker>
                </FormModelItem>
                <FormModelItem prop="endTime" class="flex justify-center">
                  <TimePicker
                    v-model="formData.endTime"
                    format="HH:mm"
                    placeholder="结束时间"
                    :allowClear="false"
                    :disabledHours="getDisabledHours"
                    :disabledMinutes="getDisabledMinutes"
                  ></TimePicker>
                </FormModelItem>
              </div>
            </FormModelItem>
          </div>
          <FormModelItem class="base_form_item my-2" label="备注" prop="remark">
            <TextArea
              placeholder="请输入备注"
              max="50"
              maxlength="15"
              v-model="formData.remark"
            ></TextArea>
          </FormModelItem>
        </div>
        <div
          class="flex items-center justify-center"
          style="position: relative; left: -12rem"
        >
          <a-button @click="handleClickCancel">取消</a-button>
          <a-button type="primary" class="ml-10" @click="handleClickConfirm"
            >确认</a-button
          >
        </div>
      </FormModel>
    </a-modal>
  </div>
</template>
<script lang="ts">
import Vue from "vue";
import {
  Cascader,
  FormModel,
  Select,
  Checkbox,
  TimePicker,
  Input,
  Modal,
  message,
  Spin,
} from "ant-design-vue";
import { LEVE_ORG } from "./const";
import outletColumns from "@/const/columns/outletColumns";
import transferTimeStampToMoment, {
  getOpeningHoursFromMoment,
  getWeekendStatusFromArr,
  transfterStrToDate,
  transfterStrToDateSafari
} from "@/utils/time/transfer";
import { getSelfOutLet } from "@/utils/outlet/index";
import { getUserMsg } from "@/utils/userMsg/userMsg";
import { Switch } from "ant-design-vue";
import { eLevel } from "@/types/level";
import { eNewRoleRelatedToBackEnd } from "@/types/role";
import HeaderSelect from "./components/HeaderSelect/index.vue";
import { fooList } from "./components/HeaderSelect/const";
import { handle建设银行excelFileChange } from "@/utils/StaffUtils/index";
import StaffService from "@/service/StaffService";
import { iStaffItem } from "@/service/StaffService/types";
import AddressService from "@/service/AddressService";
import moment from "moment";
import HeaderSelect3 from "@/components/HeaderSelect3/index.vue";
import { fooList as fooList_createOutlet } from "@/components/HeaderSelect3/const";
import { iOutLetDetail } from "@/service/AddressService/types";
// import AMap from "Amap";

const FormModelItem = FormModel.Item;
const SelectOption = Select.Option;
const CheckBoxGroup = Checkbox.Group;
const TextArea = Input.TextArea;

enum eModalType {
  create,
  edit,
}

export default Vue.extend({
  components: {
    "a-switch": Switch,
    FormModel,
    FormModelItem,
    Select,
    SelectOption,
    Checkbox,
    CheckBoxGroup,
    TimePicker,
    TextArea,
    HeaderSelect,
    Spin,
    HeaderSelect3,
  },
  data() {
    const that = this;

    const rules = {
      startTime: [{ required: true, message: "请选择开始时间" }],
      endTime: [{ required: true, message: "请选择结束时间" }],
      location: [
        {
          required: true,
          message: "请输入现详细地址",
        },
      ],
      la: [{ required: true, message: "请输入纬度" }],
      lo: [{ required: true, message: "请输入经度" }],
      remark: [
        {
          validator: (rule: any, value: any, cb: (...args: any) => any) => {
            const isOpen = (that as any).formData.isOpen;
            if (!isOpen && value.length === 0) {
              cb(new Error("请输入不营业原因"));
            } else {
              cb();
            }
          },
          trigger: "change",
        },
      ],
    };

    const editOutLetRules = {
      ...rules,
      newSecondSubBranch: [
        {
          required: true,
          message: "请输入现属二级支行",
        },
      ],
    };

    const createOutLetRules = {
      ...rules,
      firstBranch: [
        { required: true, message: "请选择一级分行", trigger: "blur" },
      ],
      secondBranch: [
        { required: true, message: "请选择二级分行", trigger: "blur" },
      ],
      firstSubBranch: [
        { required: true, message: "请选择一级支行", trigger: "blur" },
      ],
      secondSubBranch: [{ required: true, message: "请输入二级支行" }],
    };

    return {
      tableLoading: false,
      id: NaN,
      showNote: false,
      noteContent: "",
      showNoteLoading: false,
      fooList,
      fooList_createOutlet: fooList_createOutlet,
      la: "",
      lo: "",
      cascaderValue: [] as any[],
      addressSearchValue: "",
      searchPageReqParams: {
        name: "",
        phone: "",
        startTime: undefined as undefined | number,
        endTime: undefined as undefined | number,
      },
      visible: false,
      formData: {
        la: "",
        lo: "",
        firstBranch: undefined as any | undefined,
        secondBranch: undefined as any,
        firstSubBranch: undefined as any,
        secondSubBranch: "" as any,
        newSecondSubBranch: "" as any,
        location: "",
        isOpen: false as boolean,
        openDays: ["1", "2", "3", "4", "5"],
        startTime: undefined as any,
        endTime: undefined as any,
        remark: "",
      },
      createOutlet_formRules: createOutLetRules,
      formRules: editOutLetRules,
      openDaysOptions: [
        { label: "星期一", value: "1", disabled: true },
        { label: "星期二", value: "2", disabled: true },
        { label: "星期三", value: "3", disabled: true },
        { label: "星期四", value: "4", disabled: true },
        { label: "星期五", value: "5", disabled: true },
        { label: "星期六", value: "6" },
        { label: "星期日", value: "7" },
      ],
      firstBranchOptions: [] as any[],
      secondBranchOptions: [] as any[],
      firstSubBranchOptions: [] as any[],
      secondSubBranchOptions: [] as any[],
      eModalType,
      modalType: undefined as undefined | eModalType,
      dataSource: [] as any[],
      start:'',
    };
  },
  async mounted() {
    if (!this.showbranchFilter) {
      this.initTableDataSource();
    }
  },
  created() {
    // this.isCreated();
  },
  methods: {
    moment,
    // isCreated() {
    //   if (this.modalType === this.eModalType.create) {
    //     console.log(this.modalType,'this.modalType');
    //     console.log(this.eModalType.create,'this.eModalType.create');
    //   } else {
    //     console.log(this.modalType,'this.modalType');
    //     console.log(this.eModalType.create,'this.eModalType.create');
        
        
    //     // this.formData.startTime = moment("00:00", "HH:mm");
    //     // this.formData.endTime = moment("23:00", "HH:mm");
    //   }
    // },
    getDisabledHours() {
      
      let hours = [];
      let time = this.formData.startTime;
      let time2 = this.formData.endTime;
      var hour = time._d.getHours();
      var minute = time._d.getMinutes();
      var minute2 = time2._d.getMinutes();
      for (var i = 0; i < hour; i++) {
        hours.push(i);
      }
      if (minute >= minute2) {
        hours.push(hour);
      }
      return hours;
    },
    getDisabledMinutes(selectedHour: number) {
      let time = this.formData.startTime;
      selectedHour == hour;

      var hour = time._d.getHours();
      var minute = time._d.getMinutes();
      let minutes = [];
      if (selectedHour == hour) {
        for (var i = 0; i <= minute; i++) {
          minutes.push(i);
        }
      }
      return minutes;
    },
    getDisabledHours1() {
      let hours = [];
      let time1 = this.formData.startTime;
      let time2 = this.formData.endTime;
      var hour = time2._d.getHours();
      var minute2 = time2._d.getMinutes();
      var minute1 = time1._d.getMinutes();
      for (var i = hour + 1; i < 24; i++) {
        hours.push(i);
      }
      if (minute1 >= minute2) {
        hours.push(hour);
      }
      return hours;
    },
    getDisabledMinutes1(selectedHour: number) {
      let time = this.formData.endTime;
      selectedHour == hour;
      var hour = time._d.getHours();
      var minute = time._d.getMinutes();
//  console.log(this.modalType,'this.modalType');
//         console.log( this.eModalType.create,' this.eModalType.create');
      // console.log(selectedHour, "this.selectedHour");

      let minutes = [];
      if (selectedHour == hour) {
        for (var i = minute; i < 60; i++) {
          minutes.push(i);
        }
      }
      return minutes;
    },
    async handleInput(e: Event) {
      const ret = await handle建设银行excelFileChange(e);
      StaffService.getInstance().import({
        staffs: ret as any,
      });
    },
    async getLalo() {
      await AddressService.getInstance()
        .__getGpses([this.formData.location])
        .then((ret) => {
          if (ret.code === 200) {
            const position = ret.data.gps[0].split(",");
            console.log(position[0], position[1]);
            this.formData.lo = position[0];
            this.formData.la = position[1];
          }else{
            message.warn('现详细地址输入有误')
          }
        });
    },
    async clickViewNote(record: any) {
      console.log(record);
      const id = record.id;
      this.showNote = true;
      this.showNoteLoading = true;
      const ret = await AddressService.getInstance().note(id);
      if (ret.code === 200) {
        this.noteContent = ret.data.note;
        this.showNoteLoading = false;
      }
    },
    async handleFileChange(e: Event) {
      const ret = await handle建设银行excelFileChange(e);
      StaffService.getInstance().import({
        staffs: ret as iStaffItem[],
      });
    },
    setFooList(v: any[]) {
      this.fooList = [...v];
    },
    setFooList_createOutlet(v: any[]) {
      this.fooList_createOutlet = [...v];
    },
    formatDate(timeStamp: number) {
    const commonLen = new Date().getTime().toString().length
    if (timeStamp.toString().length === commonLen) {
      return moment(timeStamp).format('YYYY/MM/DD HH:mm') // September 14th 2021, 3:22:23 pm
    } else {
      return ''
    }
  },
    async clickEdit(record: iOutLetDetail) {
      this.id = record.id;
      this.modalType = eModalType.edit;
      const branchValues = this.$route.query.branchValues as string;
      // const arr = branchValues.split(",");
      this.formData.firstBranch = record.province_name;
      this.formData.secondBranch = record.city_name;
      this.formData.firstSubBranch = record.region_name;
      this.formData.secondSubBranch = record.outlet_name;
      this.formData.newSecondSubBranch = record.outlet_name;
      this.formData.location = record.location;
      this.formData.isOpen = record.is_normal_work;
      this.formData.la = record.latitude;
      this.formData.lo = record.longitude;
      this.formData.openDays = ["1", "2", "3", "4", "5"];
      if (record.weekend_status === 1) {
        this.formData.openDays.push("6");
      } else if (record.weekend_status === 2) {
        this.formData.openDays.push("7");
      } else if (record.weekend_status === 3) {
        this.formData.openDays.push("6");
        this.formData.openDays.push("7");
      }
      // const arr2 = transfterStrToDate(record.opening_hours);
      const arr2 = transfterStrToDateSafari(record.opening_hours);
      
      if (arr2?.length === 2) {
        const [startDate, endDate] = arr2;
        this.formData.startTime = moment(startDate, "HH:mm");
        this.formData.endTime = moment(endDate, "HH:mm"); 
      }
      const ret = await AddressService.getInstance().note(record.id);
      if (ret.code === 200) {
        this.formData.remark = ret.data.note;
      }

      this.firstBranchOptions = [
        {
          value: record.province_name,
          label: record.province_name,
        },
      ];
      this.secondBranchOptions = [
        {
          value: record.city_name,
          label: record.city_name,
        },
      ];
      this.firstSubBranchOptions = [
        {
          value: record.region_name,
          label: record.region_name,
        },
      ];
      this.secondSubBranchOptions = [
        {
          value: record.outlet_name,
          label: record.outlet_name,
        },
      ];
      this.visible = true;
    },
    async clickDelete(record: any) {
      const outletid = record.id;
      const ret = await StaffService.getInstance().queryStaff({
        second_sub_branch: outletid,
      });

      if (ret.code === 200 && ret.data.total == 0) {
        Modal.confirm({
          title: "删除网点",
          content: "确认删除网点？",
          okText: "确定",
          okType: "danger",
          cancelText: "取消",
          onOk: async () => {
            await AddressService.getInstance().delete({
              id: record.id,
            });
            // this.initTableDataSource();
            this.initTableDataSource();
            message.success("删除成功");
            // this.$router.go(-1);

          },
          onCancel() {},
        });
      } else {
        message.warn("请先转移该支行员工，再做删除");
      }
    },
    handleClickCancel() {
      this.visible = false;
    },
    createOutlet() {
      const form = this.$refs.createOutlet_form as FormModel;
      form.validate(async (isValid) => {
        if (isValid) {
          this.visible = false;
          const ret = await AddressService.getInstance().add({
            is_normal_work: this.formData.isOpen,
            lat_lon: `${this.formData.lo},${this.formData.la}`,
            location: this.formData.location,
            note: this.formData.remark,
            opening_hours: getOpeningHoursFromMoment(
              this.formData.startTime,
              this.formData.endTime
            ),
            province_id: this.formData.firstBranch as number,
            city_id: this.formData.secondBranch as number,
            region_id: this.formData.firstSubBranch as number,
            region_name: this.fooList_createOutlet[2].options.find(
              (i) => i.ID === this.formData.firstSubBranch
            )?.Name as string,
            name: this.formData.secondSubBranch,
            weekend_status: getWeekendStatusFromArr(this.formData.openDays),
          });
          if (ret.code === 200) {
            message.success("新增成功");
          }
        }
      });
    },
    updateOutlet() {
      const form = this.$refs.form as FormModel;
      form.validate((isValid) => {
        if (isValid) {
          this.visible = false;
          AddressService.getInstance()
            .update({
              id: this.id,
              is_normal_work: this.formData.isOpen,
              lat_lon: `${this.formData.lo},${this.formData.la}`,
              location: this.formData.location,
              name: this.formData.newSecondSubBranch,
              note: this.formData.remark,
              opening_hours: getOpeningHoursFromMoment(
                this.formData.startTime,
                this.formData.endTime
              ),
              weekend_status: getWeekendStatusFromArr(this.formData.openDays),
            })
            .then(() => {
              this.initTableDataSource();
            });
        }
      });
    },
    handleClickConfirm() {
      if (this.modalType === eModalType.create) {
        this.createOutlet();
      } else {
        this.updateOutlet();
      }
    },
    clickAddNewOnSearchPage() {
      this.visible = true;
      this.modalType = eModalType.create;
    },
    openDaysChange(openDays: any[]) {
      console.log(openDays);
    },
    handleFirstBanchChange(value: any) {
      this.formData.firstBranch = value;
    },
    handleSecondBanchChange(value: any) {
      this.formData.secondBranch = value;
    },
    handleFirstSubBanchChange(value: any) {
      this.formData.firstSubBranch = value;
    },
    handleSecondSubBanchChange(value: any) {
      this.formData.secondSubBranch = value;
    },
    handleIsOpenChange(isOpen: boolean) {
      this.formData.isOpen = isOpen;
    },
    onRangePickerChange(value: any) {
      if (value.length === 0) {
        this.searchPageReqParams.startTime = undefined;
        this.searchPageReqParams.endTime = undefined;
      } else {
        const [firstM, secondM] = value;
        firstM.hour(0);
        firstM.minute(0);
        firstM.second(0);
        secondM.hour(23);
        secondM.minute(59);
        secondM.second(59);

        this.searchPageReqParams.startTime = firstM._d.getTime();
        this.searchPageReqParams.endTime = secondM._d.getTime();
      }
    },
    onSearchOutlet(value: any[]) {
      console.log(value, "show value");
    },
    clickQuery() {
      const canQuery = this.fooList[2].value !== undefined;
      console.log(this.fooList);
      if (canQuery) {
        const branchValues = this.fooList
          .map((i) => {
            console.log(i.value);
            if (i.value) {
              return i.options.find((item) => item.ID === i.value)?.Name;
            }
          })
          .filter((item) => item)
          .toString();

        const branchIds = this.fooList
          .map((i) => {
            if (i.value) {
              return i.options.find((item) => item.ID === i.value)?.ID;
            }
          })
          .filter((item) => item)
          .toString();

        const outletName = this.fooList[3].options.find(
          (i) => i.ID === this.fooList[3].value
        )?.Name;
        this.$router.push({
          query: {
            branchValues,
            branchIds,
          },
        });
        this.initTableDataSource();
      }
    },
    afterClose() {
      if (this.modalType === eModalType.edit) {
        const form = this.$refs.form as FormModel;
        form.resetFields();
      } else {
        const form = this.$refs.createOutlet_form as FormModel;

        form.resetFields();
      }
    },
    async initTableDataSource() {
      this.tableLoading = true;
      const branchValues = this.$route.query.branchValues as string;
      const branchIds = this.$route.query.branchIds as string;
      const ids = branchIds.split(",");
      console.log(ids);
      console.log(Number(ids[ids.length - 1]), "hjskadhjkas");
      const ret = await AddressService.getInstance().getOutlets({
        id: Number(ids[ids.length - 1]),
        level: ids.length,
      });
      if (ret.code === 200) {
        this.dataSource = ret.data as any;
        this.dataSource.map((item) => {
          item.first_branch = item.province_name;
          item.second_branch = item.city_name;
          item.first_sub_branch = item.region_name;
          item.second_sub_branch = item.outlet_name;
          item.location = item.location;
          item.is_normal_work = item.is_normal_work;
          item.opening_hours = item.opening_hours;
          item.longitude = item.longitude;
          item.latitude = item.latitude;
          item.id = item.id;
        });
        // this.dataSource = [{}];
        // this.dataSource[0].first_branch = ret.data.province_name;
        // this.dataSource[0].second_branch = ret.data.city_name;
        // this.dataSource[0].first_sub_branch = ret.data.region_name;
        // this.dataSource[0].second_sub_branch = ret.data.outlet_name;
        // this.dataSource[0].location = ret.data.location;
        // this.dataSource[0].is_normal_work = ret.data.is_normal_work;
        // this.dataSource[0].opening_hours = ret.data.opening_hours;
        // this.dataSource[0].longitude = ret.data.longitude;
        // this.dataSource[0].latitude = ret.data.latitude;
        // this.dataSource[0].id = ret.data.id;
        // this.dataSource[0] = {
        //   ...this.dataSource[0],
        //   ...ret.data,
        // };
        // this.dataSource = [...this.dataSource];
      }
      this.tableLoading = false;
    },
    clickQueryOnSearchPage() {},
    clickReset() {
      (this.$refs.headerSelect as any).init();
      this.addressSearchValue = "";
    },
    clickResetOnSearchPage() {
      this.searchPageReqParams.name = "";
      this.searchPageReqParams.phone = "";
      this.searchPageReqParams.startTime = undefined;
      this.searchPageReqParams.endTime = undefined;
    },
    clickAddOutlet() {
      this.formData.startTime = moment("00:00", "HH:mm");
      this.formData.endTime = moment("23:00", "HH:mm");
     
      
      (this.$refs.headerselect3 as any)?.init();
      this.visible = true;
      this.modalType = eModalType.create;
       console.log(this.formData.startTime,' this.formData.startTime');
    },
  },
  computed: {
    outletColumns() {
      if (this.hasOperateAuth) return outletColumns;
      else {
        return outletColumns.filter((i) => !i.needAuth);
      }
    },
    hasOperateAuth() {
      const isBackAdmin =
        getUserMsg()?.newRole === eNewRoleRelatedToBackEnd.BackAdmin
      return isBackAdmin;
    },
    hasDeleteAuth() {
      const isBackAdmin =
        getUserMsg()?.newRole === eNewRoleRelatedToBackEnd.BackAdmin;
      return isBackAdmin;
    },
    showbranchFilter() {
      if (this.$route.query.branchValues) {
        return false;
      } else {
        return true;
      }
    },
    role() {
      return getUserMsg()?.newRole;
    },
    level(): number | undefined {
      return getUserMsg()?.level;
    },
    rangePickerValue(): any {
      return (
        (this.searchPageReqParams.startTime &&
          this.searchPageReqParams.endTime &&
          transferTimeStampToMoment(
            this.searchPageReqParams.startTime,
            this.searchPageReqParams.endTime
          )) ||
        undefined
      );
    },
  },
  watch: {
    fooList_createOutlet(
      newV: typeof fooList_createOutlet,
      oldV: typeof fooList_createOutlet
    ): any {
      // console.log(newV[0].value, "v");
      // this.formData.firstBranch = 1
      // this.formData.firstBranch = newV[0].value
      // console.log(this.formData, 1);
      newV.forEach((item, index) => {
        console.log(item.propName, item.value);

        (this.formData as any)[item.propName] = item.value;
      });
      // console.log(this.formData, 2);
    },
  },
});
</script>

<style lang="less">
.base_form_item {
  // justify-content: center;
  display: flex;
  /deep/ .ant-form-item-label {
    padding-right: 30px;
  }
}
</style>