<template>
  <!-- 新增弹窗 -->
  <a-modal
    v-model="show"
    :title="title"
    :centered="true"
    footer=""
    :level="level"
  >
    <a-form-model
      :model="form"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 14 }"
      ref="addForm"
      :rules="formRules"
    >
      <a-form-model-item
        label="名称"
        v-show="modalMode === eAddManagerModalMode.edit"
      >
        <div>{{ personalMsg.name }}</div>
      </a-form-model-item>
      <a-form-model-item
        label="UID"
        v-show="modalMode === eAddManagerModalMode.edit"
      >
        <div>{{ personalMsg.uid }}</div>
      </a-form-model-item>
      <a-form-model-item
        label="手机号"
        v-show="modalMode === eAddManagerModalMode.edit"
      >
        <div>{{ personalMsg.phone }}</div>
      </a-form-model-item>
      <a-form-model-item
        label="名称"
        :required="true"
        prop="name"
        v-show="modalMode === eAddManagerModalMode.create"
      >
        <a-input
          v-model="form.name"
          placeholder="请输入名称"
          style="width: 200px"
        />
      </a-form-model-item>
      <a-form-model-item
        label="手机号"
        prop="tel"
        v-show="modalMode === eAddManagerModalMode.create"
      >
        <a-input
          v-model="form.tel"
          placeholder="请输入手机号"
          style="width: 200px"
        />
      </a-form-model-item>
      <a-form-model-item
        label="初始密码"
        prop="password"
        v-show="modalMode === eAddManagerModalMode.create"
      >
        <a-input v-model="form.password" style="width: 200px" />
      </a-form-model-item>
      <a-form-model-item
        label="岗位角色"
        v-show="modalMode === eAddManagerModalMode.create"
      >
        <span class="text-sm text-black mr-2">{{ theRole }}</span>
        <!-- <a-switch @change="onChange" v-show="isManager" /> -->
        <!-- <span class="ml-2" v-show="isManager">可对同级管理员进行管理调配</span> -->
      </a-form-model-item>
      <a-form-model-item label="用户所在机构层级">
        <span class="text-sm text-black">{{ searchLevel | filterLevel }}</span>
      </a-form-model-item>
      <a-form-model-item
        label="现属一级分行"
        v-show="modalMode === eAddManagerModalMode.edit"
      >
        <div>
          {{ personalMsg.branchDetailMsg && personalMsg.branchDetailMsg.fb }}
        </div>
      </a-form-model-item>
      <a-form-model-item
        label="现属二级分行"
        v-show="modalMode === eAddManagerModalMode.edit"
      >
        <div>
          {{ personalMsg.branchDetailMsg && personalMsg.branchDetailMsg.sb }}
        </div>
      </a-form-model-item>
      <a-form-model-item
        label="现属一级支行"
        v-show="modalMode === eAddManagerModalMode.edit"
      >
        <div>
          {{ personalMsg.branchDetailMsg && personalMsg.branchDetailMsg.fsb }}
        </div>
      </a-form-model-item>
      <a-form-model-item
        label="现属二级支行"
        v-show="modalMode === eAddManagerModalMode.edit"
      >
        <div>
          {{ personalMsg.branchDetailMsg && personalMsg.branchDetailMsg.ssb }}
        </div>
      </a-form-model-item>
      <a-form-model-item
        label="现地址"
        v-show="modalMode === eAddManagerModalMode.edit"
      >
        <div>
          {{
            personalMsg.branchDetailMsg && personalMsg.branchDetailMsg.address
          }}
        </div>
      </a-form-model-item>
      <a-form-model-item
        label="选择调配级别"
        v-show="modalMode === eAddManagerModalMode.edit"
      >
        <a-select
          class="header-select-item mx-3 my-2"
          placeholder="选择调配级别"
          :value="form.level"
          @change="handleLevelChange"
        >
          <a-select-option
            v-for="option in levelOptions"
            :value="option.value"
            :key="option.value"
            >{{ option.value | filterLevel }}</a-select-option
          >
        </a-select>
      </a-form-model-item>
      <HeaderSelect
        ref="headerSelect"
        :setFooList="setFooList"
        :fooList="fooList"
        :level="level"
        :userLevel="searchLevel"
      />
      <a-form-model-item label="新地址" prop="location">
        <a-input
          class="mx-3 my-2"
          :disabled="true"
          v-model="form.location"
          style="width: 200px"
        />
      </a-form-model-item>
    </a-form-model>
    <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" @click="onConfirm">发布</a-button>
      <a-button style="margin-left: 10px" @click="show = false">取消</a-button>
    </a-form-model-item>
  </a-modal>
</template>

<script lang="ts">
import Vue, { PropType } from "vue";
import { FormModel, Switch } from "ant-design-vue";
import { eLevel } from "@/types/level";
import { LEVE_ORG } from "@/views/Root/OutletManagement/const";
import { mapMutations, mapState } from "vuex";
import {
  eAddManagerModalMode,
  eTypeOfOperatedObject,
  iBranchDetailMsg,
} from "@/store/UserManagement/types";
import HeaderSelect from "@/components/HeaderSelect2/index.vue";
import { fooList } from "@/components/HeaderSelect2/const";
import StaffService from "@/service/StaffService";
import AddressService from "@/service/AddressService";

Vue.use(Switch);

export default Vue.extend({
  components: {
    HeaderSelect,
  },
  computed: {
    formRules() {
      const rules: any = {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        tel: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        location: [],
        fooProp0: [
          {
            required: true,
            message: "请选择一级分行",
            trigger: "blur",
          },
        ],
        fooProp1: [
          {
            required: true,
            message: "请选择二级分行",
            trigger: "blur",
          },
        ],
        fooProp2: [
          {
            required: true,
            message: "请选择一级支行",
            trigger: "blur",
          },
        ],
        fooProp3: [
          {
            required: true,
            message: "请选择二级支行",
            trigger: "blur",
          },
        ],
      };
      if (this.modalMode === eAddManagerModalMode.create) {
      } else if (this.modalMode === eAddManagerModalMode.edit) {
        delete rules.name;
        delete rules.tel;
      }

      console.log(rules);

      return rules;
    },
    levelOptions() {
      const optionList = [
        { value: eLevel.firstLevel_branch },
        { value: eLevel.secondary_branch },
        { value: eLevel.firstLevel_sub_branch },
        { value: eLevel.secondary_sub_branch },
      ];
      return optionList.filter((i) => i.value >= this.searchLevel);
    },
    title(): string | undefined {
      if (this.modalMode === eAddManagerModalMode.create) {
        return "新增";
      } else if (this.modalMode === eAddManagerModalMode.edit) {
        return "调配";
      }
    },
    theRole(): string | undefined {
      if (this.typeOfOperatedObject === eTypeOfOperatedObject.manager) {
        return "管理员";
      } else if (
        this.typeOfOperatedObject === eTypeOfOperatedObject.clientManager
      ) {
        return "客户经理";
      }
    },
    isManager(): boolean {
      return this.typeOfOperatedObject === eTypeOfOperatedObject.manager;
    },
    show: {
      set(v: boolean) {
        this.setModal(v);
      },
      get(): boolean {
        return this.modalShow;
      },
    },
    bankList(): string[] {
      return ["ada", "ads", "ds", "dsa"];
    },
    labelList(): string[] {
      return this.label.slice(this.level, this.label.length);
    },
    level_org(): number {
      return LEVE_ORG;
    },
    ...mapState("UserManagement", {
      modalShow: "modalShow",
      modalMode: "modalMode",
      searchLevel: "searchLevel",
      personalMsg: "personalMsg",
      branchDetailMsg: "branchDetailMsg",
      typeOfOperatedObject: "typeOfOperatedObject",
    }),
  },
  props: {
    label: {
      type: Array as PropType<string[]>,
      default() {
        return ["一级分行", "二级分行", "一级支行", "二级支行"];
      },
    },
    level: {
      type: Number as PropType<eLevel>,
      default: 0,
    },
  },
  data() {
    return {
      eAddManagerModalMode,
      fooList,
      form: {
        name: "",
        tel: "",
        password: "abc123456",
        location: "",
        privilege: false,
        fooProp0: undefined as number | undefined,
        fooProp1: undefined as number | undefined,
        fooProp2: undefined as number | undefined,
        fooProp3: undefined as number | undefined,
        level: eLevel.firstLevel_branch,
      },
      outletName: "",
    };
  },
  methods: {
    handleLevelChange(value: any) {
      this.form.level = value;
    },
    async initFooList() {
      const list = this.fooList.map((i) => {
        return {
          ...i,
          disable: false,
          value: undefined,
          options: [],
        };
      });
      this.fooList = list;
      let branchDetailMsg: iBranchDetailMsg =
        undefined as unknown as iBranchDetailMsg;
      if (this.modalMode === eAddManagerModalMode.create) {
        branchDetailMsg = this.branchDetailMsg;
      } else if (this.modalMode === eAddManagerModalMode.edit) {
        branchDetailMsg = this.personalMsg.branchDetailMsg;
        this.form.level = this.level;
      }

      if (branchDetailMsg.fb !== undefined) {
        this.fooList[0].options = [
          { Name: branchDetailMsg.fb, ID: branchDetailMsg.fb_id },
        ];
        this.fooList[0].value = branchDetailMsg.fb_id;
        if (this.modalMode === eAddManagerModalMode.create) {
          this.fooList[0].disable = true;
        }
      }
      if (branchDetailMsg.sb !== undefined) {
        this.fooList[1].options = [
          { Name: branchDetailMsg.sb, ID: branchDetailMsg.sb_id },
        ];
        this.fooList[1].value = branchDetailMsg.sb_id;
        if (this.modalMode === eAddManagerModalMode.create) {
          this.fooList[1].disable = true;
        }
      }
      if (branchDetailMsg.fsb !== undefined) {
        this.fooList[2].options = [
          { Name: branchDetailMsg.fsb, ID: branchDetailMsg.fsb_id },
        ];
        this.fooList[2].value = branchDetailMsg.fsb_id;
        if (this.modalMode === eAddManagerModalMode.create) {
          this.fooList[2].disable = true;
        }
      }
      if (branchDetailMsg.ssb !== undefined) {
        this.fooList[3].options = [
          { Name: branchDetailMsg.ssb, ID: branchDetailMsg.ssb_id },
        ];
        this.fooList[3].value = branchDetailMsg.ssb_id;
        if (this.modalMode === eAddManagerModalMode.create) {
          this.fooList[3].disable = true;
        }
      }

      const fetchOptionListForEverySettledBranchEdit = async (
        list: typeof fooList
      ) => {
        list.forEach(async (item, index) => {
          if (index === 0) {
            const ret = await StaffService.getInstance().getBranch({
              level: eLevel.firstLevel_branch,
              page: 1,
              page_size: 10000,
            });
            if (ret.code === 200) {
              this.fooList[0].options = ret.data.item;
            }
          } else {
            const ret = await StaffService.getInstance().getBranch({
              level: index + 1,
              page: 1,
              page_size: 10000,
              parent_id: this.fooList[index - 1].value,
            });
            if (ret.code === 200) {
              this.fooList[index].options = ret.data.item;
            }
          }
        });
      };

      if (this.modalMode === eAddManagerModalMode.edit) {
        await fetchOptionListForEverySettledBranchEdit(this.fooList);
      }

      this.fooList = [...this.fooList];
      await this.fetchNextOptions();
    },
    async fetchNextOptions() {
      const fooIndex = this.fooList.findIndex(
        (item) => item.value === undefined
      );
      if (fooIndex === -1) {
      } else {
        if (fooIndex === 0) {
          /* 银行管理员添加 一级分行管理员 */
          const ret = await StaffService.getInstance().getBranch({
            level: eLevel.firstLevel_branch,
            page: 1,
            page_size: 10000,
          });
          if (ret.code === 200) {
            this.fooList[0].options = ret.data.item;
          }
        } else {
          const ret = await StaffService.getInstance().getBranch({
            level: fooIndex + 1,
            page: 1,
            page_size: 10000,
            parent_id: this.fooList[fooIndex - 1].value,
          });
          if (ret.code === 200) {
            this.fooList[fooIndex].options = ret.data.item;
          }
        }
      }
    },
    setFooList(v: any[]) {
      this.fooList = [...v];
    },
    ...mapMutations("UserManagement", {
      save: "save",
    }),
    showModal() {
      this.setModal(true);
    },
    setModal(show: boolean) {
      this.save({
        modalShow: show,
      });
    },
    onChange(checked: boolean) {
      this.form.privilege = checked;
    },
    onConfirm() {
      (this.$refs.addForm as FormModel).validate((valid) => {
        if (valid) {
          if (this.modalMode === eAddManagerModalMode.create) {
            StaffService.getInstance()
              .addNextLevel({
                attr: {
                  add_same_level: false,
                },
                level: this.searchLevel,
                name: this.form.name,
                password: this.form.password,
                phone: this.form.tel,
                second_sub_branch: this.form.fooProp3 as number,
              })
              .then(() => {
                this.save({
                  refreshMark: new Date().getTime(),
                });
              });
          } else if (this.modalMode === eAddManagerModalMode.edit) {
            StaffService.getInstance()
              .deploy({
                level: this.form.level,
                second_sub_branch: this.fooList[3].value as number,
                uuid: this.personalMsg.uid,
              })
              .then(() => {
                this.save({
                  refreshMark: new Date().getTime(),
                });
              });
          }
          this.setModal(false);
        } else {
          return false;
        }
      });
    },
    async handleOutLetName(newV: string) {
      if (newV !== "") {
        const ret = await AddressService.getInstance().getOutlet({
          outlet_name: newV,
        });
        if (ret.code === 200) {
          this.form.location = ret.data.location;
        }
      } else {
        this.form.location = "";
      }
    },
  },
  watch: {
    show(newV) {
      if (newV === true) {
        this.initFooList();
      } else {
        const form = this.$refs.addForm as FormModel;
        form.resetFields();
      }
    },
    fooList(newV: typeof fooList, oldV: typeof fooList) {
      newV.forEach((item, index) => {
        (this.form as any)[`fooProp${index}`] = item.value;
      });
      if (newV[3].value !== undefined) {
        this.outletName =
          newV[3].options.find((i) => i.ID === newV[3].value)?.Name || "";
        this.handleOutLetName(this.outletName);
      } else if(newV[3].value === undefined){
        console.log(newV[3]);
        this.outletName = "";
        this.handleOutLetName(this.outletName);
      }
    },
  },
});
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 5px;
}
</style>