<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
        >
      </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"
          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-divider type="vertical" /> -->
            <!-- <a href="javascript:;" @click="clickDelete(record)">删除</a> -->
          </template>
        </a-table>
      </div>
    </div>
    <a-modal title="查看" v-model="showNote" :footer="null">
      <spin :spinning="showNoteLoading">
        {{ noteContent }}
      </spin>
      <div class="h-5"></div>
    </a-modal>
    <a-modal v-model="visible" width="750px" :footer="null">
      <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="formRules"
        layout="horizontal"
        ref="form"
      >
        <FormModelItem class="base_form_item my-2" label="所属一级分行">
          <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="所属二级分行">
          <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="所属一级支行">
          <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="原属二级支行">
          <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"
        >
          <a-input
            v-model="formData.newSecondSubBranch"
            placeholder="请输入现属二级支行名称"
          />
        </FormModelItem>
        <FormModelItem
          class="base_form_item my-2"
          label="现详细地址"
          prop="location"
        >
          <a-input v-model="formData.location" placeholder="请输入现详细地址" />
        </FormModelItem>
        <FormModelItem class="base_form_item my-2" label="是否营业">
          <a-switch
            default-checked
            v-model="formData.isOpen"
            checked-children="是"
            un-checked-children="否"
          />
        </FormModelItem>
        <div class="flex">
          <FormModelItem class="base_form_item my-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" placeholder="纬度" v-model="formData.la" />
            <a-button type="primary" @click="getLalo">自动获取</a-button>
          </FormModelItem>
        </div>
        <div class="flex">
          <div>
            <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>
            </FormModelItem>
            <FormModelItem prop="startTime">
              <TimePicker
                v-model="formData.startTime"
                format="HH:mm"
                placeholder="开始时间"
              ></TimePicker>
            </FormModelItem>
            <FormModelItem prop="endTime">
              <TimePicker
                v-model="formData.endTime"
                format="HH:mm"
                placeholder="结束时间"
              ></TimePicker>
            </FormModelItem>
          </div>
          <FormModelItem class="base_form_item my-2" label="备注" prop="remark">
            <TextArea
              placeholder="请输入备注"
              max="50"
              v-model="formData.remark"
            ></TextArea>
          </FormModelItem>
        </div>
        <div class="flex items-center justify-center">
          <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,
  Form,
} from "ant-design-vue";
import { LEVE_ORG } from "./const";
import outletColumns from "@/const/columns/outletColumns";
import transferTimeStampToMoment, {
  getOpeningHoursFromMoment,
  getWeekendStatusFromArr,
  transfterStrToDate,
} 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 { FormItem } from "ant-design-vue/types/form/form-item";

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-cascader": Cascader,
    "a-switch": Switch,
    FormModel,
    FormModelItem,
    Select,
    SelectOption,
    Checkbox,
    CheckBoxGroup,
    TimePicker,
    TextArea,
    HeaderSelect,
    Spin,
  },
  data() {
    const that = this;
    return {
      id: NaN,
      showNote: false,
      noteContent: "",
      showNoteLoading: false,
      fooList,
      la: "",
      lo: "",
      cascaderValue: [] as any[],
      addressSearchValue: "",
      searchPageReqParams: {
        name: "",
        phone: "",
        startTime: undefined as undefined | number,
        endTime: undefined as undefined | number,
      },
      outletColumns,
      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: "",
      },
      formRules: {
        startTime: [{ required: true, message: "请选择开始时间" }],
        endTime: [{ required: true, message: "请选择结束时间" }],
        newSecondSubBranch: [
          {
            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",
          },
        ],
      },
      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[],
    };
  },
  async mounted() {
    if (!this.showbranchFilter) {
      this.initTableDataSource();
    }
  },
  methods: {
    async handleInput(e: Event) {
      const ret = await handle建设银行excelFileChange(e);
      StaffService.getInstance().import({
        staffs: ret as any,
      });
    },
    getLalo() {
      if ("geolocation" in window.navigator) {
        window.navigator.geolocation.getCurrentPosition((position) => {
          this.formData.la = position.coords.latitude.toString();
          this.formData.lo = position.coords.longitude.toString();
          const form = this.$refs.form as FormModel;
          form.validateField(["la", "lo"], (err) => {});
        }, (error)=>{
          message.error('获取失败')
        });
      }else{
        message.error("浏览器不支持获取GPS")
      }
    },
    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];
    },
    async clickEdit(record: any) {
      this.id = record.id;
      this.modalType = eModalType.edit;
      const branchValues = this.$route.query.branchValues as string;
      const arr = branchValues.split(",");
      this.formData.firstBranch = arr[0];
      this.formData.secondBranch = arr[1];
      this.formData.firstSubBranch = arr[2];
      this.formData.secondSubBranch = arr[3];
      this.formData.newSecondSubBranch = arr[3];
      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);
      if (arr2?.length === 2) {
        const [startDate, endDate] = arr2;
        this.formData.startTime = moment(startDate);
        this.formData.endTime = moment(endDate);
      }
      const ret = await AddressService.getInstance().note(record.id);
      if (ret.code === 200) {
        this.formData.remark = ret.data.note;
      }

      this.firstBranchOptions = [
        {
          value: arr[0],
          label: arr[0],
        },
      ];
      this.secondBranchOptions = [
        {
          value: arr[1],
          label: arr[1],
        },
      ];
      this.firstSubBranchOptions = [
        {
          value: arr[2],
          label: arr[2],
        },
      ];
      this.secondSubBranchOptions = [
        {
          value: arr[3],
          label: arr[3],
        },
      ];
      this.visible = true;
    },
    clickDelete(record: any) {
      Modal.confirm({
        title: "删除网点",
        content: "确认删除网点？",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          return new Promise((r) => {
            setTimeout(r, 1000);
          });
        },
        onCancel() {},
      });
    },
    handleClickCancel() {
      this.visible = false;
    },
    handleClickConfirm() {
      const form = this.$refs.form as FormModel;
      form.validate((isValid) => {
        if (isValid) {
          AddressService.getInstance().update({
            id: this.id,
            is_normal_work: this.formData.isOpen,
            lat_lon: `${this.formData.la},${this.formData.lo}`,
            location: this.formData.location,
            note: this.formData.remark,
            opening_hours: getOpeningHoursFromMoment(
              this.formData.startTime,
              this.formData.endTime
            ),
            weekend_status: getWeekendStatusFromArr(this.formData.openDays),
          });
          this.visible = false;
        }
      });
    },
    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[3].value !== undefined;
      if (canQuery) {
        const branchValues = this.fooList
          .map((i) => {
            return i.options.find((item) => item.ID === i.value)?.Name;
          })
          .toString();

        const outletName = this.fooList[3].options.find(
          (i) => i.ID === this.fooList[3].value
        )?.Name;
        this.$router.push({
          query: {
            branchValues,
          },
        });
        this.initTableDataSource();
      }
    },
    async initTableDataSource() {
      const branchValues = this.$route.query.branchValues as string;
      const arr = branchValues.split(",");
      const second_sub_branch = arr[3];

      this.dataSource = [
        {
          first_branch: arr[0],
          second_branch: arr[1],
          first_sub_branch: arr[2],
          second_sub_branch: arr[3],
        },
      ];
      const ret = await AddressService.getInstance().getOutlet({
        outlet_name: second_sub_branch,
      });
      if (ret.code === 200) {
        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];
      }
    },
    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;
    },
  },
  computed: {
    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
      );
    },
  },
});
</script>

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