<template>
    <!-- 添加或修改菜单对话框 -->
    <el-dialog
      title="导入是否零申报"
      v-model="visible"
      width="680px"
      append-to-body
      draggable
      :close-on-click-modal = "false"
    >
      <el-form
        ref="companyRef"
        :model="form"
        size="small"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col v:span="24">
            <el-form-item label="上传">
              <el-upload
                ref="uploadRef"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
              >
                <el-icon class="el-icon--upload">
                  <upload-filled />
                </el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip text-center">
                    <div class="el-upload__tip">
                      <!-- <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据 -->
                    </div>
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link
                      type="primary"
                      :underline="false"
                      style="font-size: 12px; vertical-align: baseline"
                      @click="importTemplate"
                      >下载模板</el-link
                    >
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            icon="Finished"
            size="small"
            @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel" icon="close" size="small">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  
  <script setup>
  import { getToken, getTenant } from "@/utils/auth";
  import {
    addCompany,
    importCompanyZero,
    listCompany,
  } from "@/api/business/crm/company";
  import CustomerFormCom from "@/components/CustomerFormCom";
  import { listChannel } from "@/api/business/channel";
  import useUserStore from "@/store/modules/user";
  import { listUser } from "@/api/system/user";
  import { listSource } from "@/api/settings/source";
  import { deepClone } from "@/utils";
  import { ref } from "vue";
  // import { incomeDefault, taxTypes, confirmDefault } from "@/utils/default"
  const { proxy } = getCurrentInstance();
  /** 父组件传参 */
  const props = defineProps({
    getList: {
      type: Function,
      default: () => {},
    },
  });
  const { getList } = toRefs(props);
  /** 字典数组区 */
  const { develop_type } = proxy.useDict("develop_type");
  /** 表单抽屉 页变量 */
  const title = ref("");
  const loading = ref(false);
  const multiple = ref(true);
  const visible = ref(false);
  
  const editStatus = ref(false);
  const sourceCategoryId = ref("");
  const isFullscreen = ref(false);
  const currentSource = ref({});
  const addDetailNum = ref(1);
  const currentMember = {};
  const provinces = ref(proxy.region.getProvinces());
  provinces.value.unshift({ code: "", name: "全部" });
  const cities = ref([]);
  const districts = ref([]);
  
  const sourceCategories = ref([]);
  

  
  const webHost = import.meta.env.VITE_APP_BASE_API;
  
  const setHeaders = {
    Authorization: getToken(),
  };
  const data = reactive({
    form: {},
    followData: {},
    rules: {
      name: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
      sourceCategoryName: [
        { validator: sourceValidator, trigger: "change" },
        { required: true, message: "客户来源不能为空", trigger: "change" },
      ],
    },
  });
  const addComRef = ref(null);
  
  /*** 客户导入参数 */
  const upload = reactive({
    // 是否禁用上传
    isUploading: false,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken(), tenantId: getTenant() },
    // 上传的地址
    url: "/ezhizao-yzbh-crm/business/company/importZero",
  });
  
  function sourceValidator(rule, value, callback) {
    console.log(form.value.reffererDataSource, form.value.sourceName);
    if (form.value.sourceCategoryName === "") {
      callback(new Error("来源类型不能为空"));
      return;
    }
    if (
      form.value.referrerDataSource !== "" &&
      form.value.referrerDataSource != null &&
      form.value.sourceName === ""
    ) {
      callback(new Error("来源不能为空"));
      return;
    }
    return callback();
  }
  
  //设置负责人
  function handleSelectEmployee(item) {
    form.value.leaderId = item.userId;
    form.value.leaderName = item.nickName;
  }
  
  //设置客服
  function handleSelect(item) {
    form.value.adviserId = item.userId;
    form.value.adviserName = item.nickName;
  }
  
  function handlerChangeCategory(value) {
    form.value.sourceId = null;
    form.value.sourceName = "";
    handlerSelectCategory();
  }
  
  function handlerSelectCategory() {
    form.value.sourceCategoryId = sourceCategoryId.value;
    // formData.value.referrerDataSource = currentSource.value.referrerDataSource
    const index = sourceCategories.value.findIndex(
      (l) => l.id === sourceCategoryId.value
    );
    currentSource.value = index >= 0 ? sourceCategories.value[index] : {};
    var item = sourceCategories.value.find(
      (emp) => emp.id === sourceCategoryId.value
    );
    if (item) {
      form.value.sourceCategoryName = item.title;
      form.value.referrerDataSource = item.referrerDataSource;
    }
  }
  
  /** 输入框输出建议 */
  function querySearchAsync(queryString, cb) {
    const query = { keyword: queryString };
    listUser(query).then((res) => {
      cb(res.rows);
    });
  }
  
  const contactorEmptyData = {
    id: null,
    name: "",
    position: "",
    gender: "男",
    phone: "",
    email: "",
    isMain: "是",
    remark: "",
  };
  
  const companyEmptyData = {
    id: null,
    code: "",
    name: "",
    oldName: "",
    shortName: "",
    ownerId: "",
    ownerName: "",
    sourceCategoryId: "",
    sourceCategoryName: "",
    sourceId: "",
    sourceName: "",
    stageId: "",
    stageName: "",
    phone: "",
    email: "",
    contactAddress: "",
    remark: "",
    socialCreditCode: "",
    mainBusinessId: "",
    mainBusinessName: "",
    typeId: "",
    typeName: "",
    legalRepresentative: "",
    foundationDate: "",
    licenceDate: "",
    businessStartDate: "",
    collectionMethod: "",
    businessEndDate: "",
    isPermanentlyEffective: "",
    registerMoney: "",
    registerMoneyUnitId: "",
    registerMoneyUnitName: "",
    provinceCode: "",
    province: "",
    cityCode: "",
    city: "",
    districtCode: "",
    district: "",
    address: "",
    businessField: "",
    taxTypeId: "",
    taxTypeName: "",
    taxDeclarationCategoryId: "",
    taxDeclarationCategoryName: "",
    isZero: "",
    taxDishId: "",
    taxDishName: "",
    competentTaxAuthority: "",
    annualIncome: "",
    taxType: "",
    taxCollectorName: "",
    taxCollectorPhone: "",
    taxMonth: "",
    openingBank: "",
    bankAccount: "",
    companyTags: [],
    companyTagIds: [],
    contactors: [],
    serviceTeams: [],
    companyFiles: [],
    stores: [],
    creatorId: useUserStore().user.id,
  };
  
  const followQuery = ref({});
  const { form, rules, followData } = toRefs(data);
  
  /***********************  表单页方法 ****************************/
  
  /** 抽屉打开 */
  function open() {
    reset();
    form.value.leaderName = useUserStore().user.nickName;
    form.value.leaderId = useUserStore().user.userId;
    visible.value = true;
  }
  
  function init() {
    listSource()
      .then((res) => {
        // console.log(res)
        sourceCategories.value = res.rows;
        // console.log(sourceCategories.value)
      })
      .catch((err) => {
        console.log(err);
      });
  }
  
  function reset() {
    form.value = deepClone(companyEmptyData);
    // console.log(addComRef.value)
    if (addComRef.value != null) addComRef.value.reset();
  }
  
  function cancel() {
    visible.value = false;
  }
  
  function submitForm() {
      submitFileForm();
  }
  
  const importTemplate = () => {
    // proxy.download('/business/company/importTemplate', {}, `company_template${new Date().getTime()}.xlsx`)
    importCompanyZero();
  };
  /**文件上传中处理 */
  const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
  };
  /** 文件上传成功处理 */
  const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$refs["uploadRef"].handleRemove(file);
    proxy.$alert(
      "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
      "导入结果",
      { dangerouslyUseHTMLString: true }
    );
    getList.value();
  };
  /** 提交上传文件 */
  function submitFileForm() {
    proxy.$refs["uploadRef"].submit();
  }
  
  // 暴露给父组件的方法
  defineExpose({
    open,
  });
  init();
  </script>
  
  <style></style>