<script setup lang="ts">
import { httpAdd, httpUpdate } from "/@/api/interest/companyAccount";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { reactive, ref, watch, nextTick } from "vue";
import { useNav } from "/@/layout/hooks/nav";
import { isMobile } from "/@/utils/validate";
import CompanyModal from "./components/company-modal.vue";
import { type menuType } from "./types";
import { useUserInfo } from "/@/hooks/core/useUser";

const { logout } = useNav();
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();

const props = defineProps({
  itemId: {
    type: String,
    default: ""
  },
  showModel: {
    type: Boolean,
    default: false
  },
  isDetails: {
    type: String,
    default: "add"
  },
  sitem: {
    type: Object as PropType<menuType>
  }
});

const defaultCompany = ref<boolean[]>([]);
let defaultCompanyNo = "";

const showModelThis = ref(false);
const emit = defineEmits<{
  (e: "cancel"): void;
  (e: "refresh"): void;
}>();
const id = ref("");
const editType = ref("add");
const formModel = {
  id: "", //账户id
  nickname: "", //真实姓名
  mobile: "", //手机号
  companyArr: []
};

const tableRef = ref<any>(null);
const ruleForm = reactive<menuType>({ ...formModel });
const companyModalRef = ref<InstanceType<typeof CompanyModal> | null>(null);
const { isSuperUser } = useUserInfo();

let originCompanyArr: any[] = [];
const rules = reactive<FormRules>({
  nickname: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { min: 2, max: 12, message: "长度在 2 到 12 个字符", trigger: "blur" }
  ],
  mobile: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("手机号不能为空！"));
        } else if (!isMobile(value)) {
          callback(new Error("手机号格式不正确！"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  companyArr: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value.length === 0) {
          callback(new Error("请选择业务公司"));
        } else {
          callback();
        }
      }
    }
  ]
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  if (!defaultCompanyNo) {
    ElMessage.warning("请选择默认公司");
    return;
  }

  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (loading.value === true) return;
      const model = Object.assign({}, ruleForm);

      if (editType.value === "add") delete model.id;
      const current = model.companyArr.map(({ companyCode }) => companyCode);
      const dels = originCompanyArr
        .filter(({ companyCode }) => !current.includes(companyCode))
        .map(({ companyCode, companyName, id }) => ({
          id,
          companyCode,
          companyName,
          is_del: 1,
          is_main: "0"
        }));

      const orgs = originCompanyArr
        .filter(({ companyCode }) => current.includes(companyCode))
        .map(({ companyCode, companyName, id }) => ({
          id,
          companyCode,
          companyName,
          is_del: 0,
          is_main: "0"
        }));

      const adds = model.companyArr
        .filter(({ companyCode: code }) => {
          return (
            !dels.find(({ companyCode }) => companyCode === code) &&
            !orgs.find(({ companyCode }) => companyCode === code)
          );
        })
        .map(({ companyCode, companyName, id }) => ({
          id,
          companyCode,
          companyName,
          is_main: "0",
          is_del: 0
        }));

      model.companyArr = [...dels, ...orgs, ...adds];

      model.companyArr.forEach(item => {
        if (item.companyCode === defaultCompanyNo) {
          item.is_main = "1";
        }
      });

      loading.value = true;
      const { code, message } =
        editType.value === "add"
          ? await httpAdd(model)
          : await httpUpdate(model);
      loading.value = false;

      if (code === 0) {
        ElMessage.success(titleType.value + "成功！");
        showModelThis.value = false;
        emit("refresh");
      } else if (code > 100 && code < 140) {
        showModelThis.value = false;
        logout();
      } else {
        ElMessage.error(message);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = async (formEl: FormInstance | undefined, item) => {
  if (formEl) {
    formEl.clearValidate();
    formEl.resetFields();
  }

  await nextTick(async () => {
    for (let key in ruleForm) {
      if (key === "companyArr" && item["company_relaton"]) {
        if (editType.value !== "add") {
          item["company_relaton"].forEach(item => {
            ruleForm.companyArr.push({ ...item });
          });
        } else {
          ruleForm.companyArr = [];
        }
      } else {
        ruleForm[key] = item[key];
      }
    }
  });

  originCompanyArr = item.company_relaton?.map(item => ({ ...item })) || [];

  if (editType.value === "add") {
    ruleForm.companyArr = [];
    originCompanyArr = [];
  }
};

const closeDialog = () => {
  showModelThis.value = false;
  defaultCompany.value = [];
  ruleForm.companyArr = [];
  defaultCompanyNo = "";
  emit("cancel");
};

const loading = ref(true);
const titleType = ref("");
async function initForm(item: Object) {
  loading.value = true;
  switch (editType.value) {
    case "add":
      titleType.value = "新建账号";
      break;
    case "edit":
      titleType.value = "编辑账号";
      break;
    case "view":
      titleType.value = "账号详情";
      break;
    default:
      titleType.value = "新建账号";
  }
  resetForm(ruleFormRef.value, item);
  loading.value = false;
}

function handleDelete(index) {
  ruleForm.companyArr.splice(index, 1);
  if (defaultCompany.value[index]) {
    defaultCompanyNo = "";
  }
  defaultCompany.value.splice(index, 1);

  if (ruleForm.companyArr.length >= 1) {
    defaultCompany.value[index] = true;
    const current = ruleForm.companyArr[index];

    if (current) {
      defaultCompanyNo = ruleForm.companyArr[index].companyCode;
      defaultCompany.value[index] = true;
      return;
    }

    defaultCompanyNo = ruleForm.companyArr[index - 1].companyCode;
    defaultCompany.value[index - 1] = true;
  }
}

function handleChoose(companys) {
  const codes = ruleForm.companyArr.map(({ companyCode }) => companyCode);

  companys.forEach(item => {
    if (!codes.includes(item.companyNo)) {
      const { companyNo, company_name } = item;
      ruleForm.companyArr.push({
        companyCode: companyNo,
        companyName: company_name
      });
    }
  });

  defaultCompany.value = ruleForm.companyArr.map(() => false);

  const index = ruleForm.companyArr.findIndex(
    ({ companyCode }) => companyCode === defaultCompanyNo
  );

  if (index >= 0) {
    defaultCompany.value[index] = true;
  }
}

watch(
  () => {
    return props.showModel;
  },
  () => {
    const { showModel, itemId, isDetails, sitem } = props as any;
    showModelThis.value = showModel;

    if (showModelThis.value) {
      id.value = itemId;
      editType.value = isDetails;
      if (isDetails !== "add") {
        initForm(sitem);
      } else {
        initForm(formModel);
      }
    }

    if (editType.value === "edit" || editType.value === "view") {
      const index = sitem.company_relaton.findIndex(
        ({ is_main }) => String(is_main) === "1"
      );

      if (index >= 0) {
        defaultCompany.value = sitem.company_relaton.map(() => false);
        defaultCompanyNo = sitem.company_relaton[index].companyCode;
        defaultCompany.value[index] = true;
      }
    }
  }
);

function handleDefaultCompanyChange(index: number) {
  defaultCompany.value.forEach((_, index) => {
    defaultCompany.value[index] = false;
  });

  defaultCompanyNo = ruleForm.companyArr[index].companyCode;
  defaultCompany.value[index] = true;
}
</script>

<template>
  <el-dialog
    :close-on-press-escape="false"
    v-model="showModelThis"
    append-to-body
    :width="'900px'"
    center
    :title="titleType"
    v-loading="loading"
    @close="closeDialog"
  >
    <el-form
      class="demo-ruleForm"
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="90px"
      :size="formSize"
      status-icon
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="真实姓名" prop="nickname">
            <el-input
              v-model="ruleForm.nickname"
              :disabled="editType === 'view'"
              placeholder="真实姓名"
            /> </el-form-item
        ></el-col>
        <el-col :span="24">
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="ruleForm.mobile"
              :disabled="editType === 'view'"
              :maxlength="11"
              placeholder="手机号"
            /> </el-form-item
        ></el-col>
        <el-col :span="24">
          <el-form-item label="业务公司" prop="companyArr">
            <el-table
              :data="ruleForm.companyArr"
              border
              size="small"
              row-key="companyCode"
              reserve-selection
              ref="tableRef"
            >
              <el-table-column label="默认公司" width="80px">
                <template #="{ $index }">
                  <div class="w-full flex justify-center">
                    <el-checkbox
                      :disabled="editType === 'view'"
                      v-model="defaultCompany[$index]"
                      @change="() => handleDefaultCompanyChange($index)"
                    />
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="公司编号" prop="companyCode" />
              <el-table-column label="公司名称" prop="companyName" />

              <el-table-column
                v-if="editType !== 'view' && isSuperUser"
                width="100px"
                label="操作"
              >
                <template #header>
                  <div class="w-full flex justify-between items-center">
                    <div>操作</div>
                    <ElButton
                      text
                      type="primary"
                      @click="() => companyModalRef.onDisplay()"
                      >添加</ElButton
                    >
                  </div>
                </template>

                <template #="{ $index }">
                  <ElButton
                    text
                    type="danger"
                    @click="() => handleDelete($index)"
                    >删除</ElButton
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item></el-col
        >
      </el-row>
      <el-col :span="24" class="clear">
        <el-button
          v-if="editType === 'add' || editType === 'edit'"
          type="primary"
          class="fr"
          style="margin: 0 0 0 16px"
          @click="submitForm(ruleFormRef)"
          :loading="loading"
          >保存</el-button
        >
        <el-button class="fr" style="margin: 0 0 0 16px" @click="closeDialog"
          >关闭</el-button
        >
      </el-col>
    </el-form>

    <CompanyModal ref="companyModalRef" @choose="handleChoose" />
  </el-dialog>
</template>
