<template>
  <!-- 添加或修改菜单对话框 -->
  <el-dialog
    title="合同导入"
    v-model="visible"
    width="680px"
    append-to-body
    draggable
    :close-on-click-modal = "false"
  >
    <el-form
      ref="menuRef"
      :model="form"
      size="small"
      :rules="rules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="24">
          <el-radio-group v-model="addType">
            <el-radio-button :label="1">循环订单导入</el-radio-button>
            <el-radio-button :label="2">单次订单导入</el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传">
            <el-upload
              ref="uploadRef"
              :limit="1"
              accept=".xlsx, .xls"
              :headers="addType === 1 ? uploadLoop.headers : uploadOnce.headers"
              :action="
                (addType === 1 ? uploadLoop.url : uploadOnce.url) +
                '?updateSupport=' +
                (addType === 1
                  ? uploadLoop.updateSupport
                  : uploadOnce.updateSupport)
              "
              :fileList="fileList"
              :before-upload="handleBeforeUpload"
              :disabled="
                addType === 1 ? uploadLoop.isUploading : uploadOnce.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格式文件。文件大小限制为&lt;50Mb</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 icon="Clsoe" size="small" @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>


<script setup>
import { getToken, getTenant } from "@/utils/auth";
import useUserStore from "@/store/modules/user";
import { deepClone } from "@/utils";
// import { incomeDefault, taxTypes, confirmDefault } from "@/utils/default"
import {
  exportLoopTemplate,
  exportOnceTemplate,
  importLoop,
  importOnce,
} from "@/api/business/crm/contract";
const { proxy } = getCurrentInstance();
/** 父组件传参 */
const props = defineProps({
  getList: {
    type: Function,
    default: () => {},
  },
});
const { getList } = toRefs(props);
/** 字典数组区 */
/** 表单抽屉 页变量 */
const fileList = ref([]);
const visible = ref(false);

const addType = ref(1);
const webHost = import.meta.env.VITE_APP_BASE_API;

const setHeaders = {
  Authorization: getToken(),
};

const data = reactive({
  form: {},
  followData: {},
});
const addComRef = ref(null);

/*** 客户导入参数 */
const uploadLoop = reactive({
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken(), tenantId: getTenant() },
  // 上传的地址
  url: "/ezhizao-yzbh-crm/business/archive/order/importLoop",
});
const uploadOnce = reactive({
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken(), tenantId: getTenant() },
  // 上传的地址
  url: "/ezhizao-yzbh-crm/business/archive/order/importOnce",
});

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();
  visible.value = true;
}

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 = () => {
  if (addType.value === 1) {
    // 循环
    exportLoopTemplate();
  } else if (addType.value === 2) {
    // 单次
    exportOnceTemplate();
  }
};

function handleBeforeUpload(file) {
  console.log(file);
  if (
    file.type !==
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" &&
    file.type !== "application/vnd.ms-excel"
  ) {
    proxy.$modal.msgError("请选择excel文件");
    return false;
  }
  return true;
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  if (addType === 1) {
    uploadLoop.isUploading = true;
  } else {
    uploadOnce.isUploading = true;
  }
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  if (addType === 1) {
    uploadLoop.open = false;
    uploadLoop.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();
  } else {
    uploadOnce.open = false;
    uploadOnce.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,
});
</script>

<style></style>