<script setup lang="ts">
import { httpAdd, httpUpdate, httpBusinesslist } 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";

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 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: "", //手机号
  companyNo: ""
};

const ruleForm = reactive<menuType>({ ...formModel });
const rules = reactive<FormRules>({});
  
const companies = ref([])

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

      const { code, message } = 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);
    }
  });
};


async function requestBussines(){
  const res = await httpBusinesslist({})
  companies.value = res.data
}


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,
              is_main: item.is_main === "1"
            });
          });
        } else {
          ruleForm.companyArr = [];
        }
      } else {
        ruleForm[key] = item[key];
      }
    }
  });
};

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

const loading = ref(true);
const titleType = ref("");
async function initForm(item: Object) {
  loading.value = true;
  titleType.value = "设置部门"
  await requestBussines()
  resetForm(ruleFormRef.value, item);
  loading.value = false;
}


function handleChoose(companys) {
  const codes = ruleForm.companyArr.map(({ companyCode }) => companyCode);
  companys.forEach(item => {
    if (!codes.includes(item.companyNo)) {
      const { companyNo, company_name } = item;
      // eslint-disable-next-line prettier/prettier
      ruleForm.companyArr.push({
        companyCode: companyNo,
        companyName: company_name,
        is_main: false
      });
    }
  });
}

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);
      }
    }
  }
);

function handleDefaultCompanyChange(index: number) {
  ruleForm.companyArr.forEach(
    (item, _index) => (item.is_main = index === _index)
  );
}
</script>

<template>
  <el-dialog
    :close-on-press-escape="false"
    :close-on-click-modal="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="companyNo">
              <el-select v-model="ruleForm.companyNo">
                <el-option />
              </el-select>
            </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>
  </el-dialog>
</template>
