<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 :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 v-if="addType === 1" :span="24">
          <el-form-item label="客户名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入客户名称" />
          </el-form-item>
        </el-col>
        <el-col v-if="addType === 1" :span="24">
          <el-form-item label="客户来源" prop="">
            <CustomerFormCom
              :edit-status="true"
              :form-data="form"
              :source-categories="sourceCategories"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="addType === 1" :span="24">
          <el-form-item label="负责人">
            <el-autocomplete
              :fetch-suggestions="querySearchAsync"
              style="width: 100%"
              v-model="form.leaderName"
              placeholder="请选择负责人"
              popper-class="my-autocomplete"
              @select="handleSelectEmployee"
            >
              <template #default="{ item }">
                <div
                  style="
                    display: flex;
                    flex-direction: row;
                    justify-content: space-between;
                  "
                >
                  <div class="name" style="font-size: 12px">
                    {{ item.nickName }}
                  </div>
                  <span class="code" style="font-size: 10px; color: darkgrey">{{
                    item.userName
                  }}</span>
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="客服">
            <el-autocomplete
              :fetch-suggestions="querySearchAsync"
              style="width: 100%"
              v-model="form.adviserName"
              placeholder="请选择客服"
              popper-class="my-autocomplete"
              @select="handleSelect"
            >
              <template #default="{ item }">
                <div
                  style="
                    display: flex;
                    flex-direction: row;
                    justify-content: space-between;
                  "
                >
                  <div class="name" style="font-size: 12px">
                    {{ item.nickName }}
                  </div>
                  <span class="code" style="font-size: 10px; color: darkgrey">{{
                    item.userName
                  }}</span>
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col v-if="addType === 2" :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 size="small" icon="Close" @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>


<script setup>
import { getToken, getTenant } from "@/utils/auth";
import { addCompany } from "@/api/business/crm/company";
import CustomerFormCom from "@/components/CustomerFormCom";
import { listUser } from "@/api/system/user";
import { listChannel } from "@/api/business/channel";
import { listCompany } from "@/api/business/crm/company";
import useUserStore from "@/store/modules/user";
import { listSource } from "@/api/settings/source";
import { deepClone } from "@/utils";
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 isFullscreen = ref(false);
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 addType = ref(1);

watch(addType, (value) => {
  switch (value) {
    case "1":
      break;
    case "2":
      break;
    default:
      break;
  }
});

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" }],
    sourceName: [{ required: true, message: "来源不能为空", trigger: "blur" }],
  },
});

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

/** 输入框输出建议 */
function querySearchAsync(queryString, cb) {
  const query = { keyword: queryString };
  listUser(query).then((res) => {
    cb(res.rows);
  });
}

//设置负责人
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;
}

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

function cancel() {
  visible.value = false;
}

function submitForm() {
  if (addType.value === 1) {
    proxy.$refs["companyRef"].validate((valid) => {
      if (valid) {
        addCompany(form.value)
          .then((res) => {
            console.log(res);
            visible.value = false;
            getList.value();
            // emit("success");
          })
          .catch((err) => {
            console.log(err);
          });
      }
    });
  } else {
    submitFileForm();
  }
}

const importTemplate = () => {
  proxy.download(
    "/business/company/importTemplate",
    {},
    `company_template${new Date().getTime()}.xlsx`
  );
};
/**文件上传中处理 */
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>