<template>
  <!-- 添加或修改菜单对话框 -->
  <el-dialog
    title="客户详情"
    v-model="visible"
    width="500px"
    append-to-body
    draggable
    :close-on-click-modal = "false"
  >
    <el-form
      ref="details"
      class="master-container"
      size="small"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-row>
        <div class="details-container" style="margin-top: 0px">
          <el-row :gutter="24" style="margin-top: 5px">
            <el-col :span="24">
              <el-form-item label="客户名称：" required prop="name">
                <el-input
                  v-if="editStatus"
                  v-model.trim="form.name"
                  size="small"
                  type="text"
                  placeholder="客户名称"
                  :clearable="true"
                />
                <span v-else>{{ form.name }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="年收入：" prop="annualIncome">
                <el-select
                  style="width: 100%"
                  v-if="editStatus"
                  v-model="form.annualIncome"
                  placeholder="请选择年收入"
                >
                  <el-option
                    v-for="item in incomeDefault"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{ form.annualIncome }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="税号：" required prop="socialCreditCode">
                <el-input
                  v-if="editStatus"
                  v-model.trim="form.socialCreditCode"
                  size="small"
                  type="text"
                  placeholder="税号"
                  :clearable="true"
                />
                <span v-else>{{ form.socialCreditCode }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24" style="margin-top: 5px">
            <el-col :span="24">
              <el-form-item label="是否零申报：">
                <el-select
                  v-if="editStatus"
                  v-model="zero"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in yesOrNo"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{
                  form.isZero === 1 ? "是" : form.isZero === 0 ? "否" : ""
                }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24" style="margin-top: 5px">
            <el-col :span="24">
              <el-form-item label="纳税性质：" required prop="taxType">
                <el-select
                  style="width: 100%"
                  v-if="editStatus"
                  v-model="form.taxType"
                  placeholder="请选择纳税性质"
                  size="small"
                  :clearable="true"
                  @change="taxTypeChange"
                >
                  <el-option
                    v-for="item in taxTypes"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{ form.taxType }} </span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="征收方式：" required prop="collectionMethod">
                <el-select
                  style="width: 100%"
                  v-if="editStatus"
                  v-model="form.collectionMethod"
                  placeholder="请选择征收方式"
                  size="small"
                  :clearable="true"
                >
                  <el-option
                    v-for="item in collectionMethods"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{ form.collectionMethod }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="form.collectionMethod === '定期定额'" :span="15">
              <el-form-item label="定额金额：" required>
                <el-input-number
                  v-if="editStatus"
                  style="width: 100%"
                  v-model="form.quotaAmount"
                  placeholder="请输入定额金额"
                  :min="0"
                  :precision="2"
                  controls-position="right"
                  :controls="false"
                  size="small"
                />
                <span v-else>{{ form.quotaAmount }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" style="margin-top: 5px">
            <el-col :span="24">
              <el-form-item label="注册省市区：" required prop="provinceCode">
                <template v-if="editStatus">
                  <el-select
                    v-model="form.provinceCode"
                    placeholder="省份"
                    style="width: 33%"
                    @change="handleSelectProvince"
                  >
                    <el-option
                      v-for="item in provinces"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                  <el-select
                    v-model="form.cityCode"
                    placeholder="城市"
                    style="width: 33%"
                    @change="handleSelectCity"
                  >
                    <el-option
                      v-for="item in cities"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                  <el-select
                    v-model="form.districtCode"
                    placeholder="行政区"
                    style="width: 34%"
                    @change="handleSelectDistrict"
                  >
                    <el-option
                      v-for="item in districts"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </template>
                <span v-else>{{
                  form.province +
                  (form.city ? " - " + form.city : "") +
                  (form.district ? " - " + form.district : "")
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="负责人：">
                <template v-if="editStatus">
                  <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>
                </template>
                <span v-else>{{ form.leaderName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="客服：">
                <template v-if="editStatus">
                  <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>
                </template>
                <span v-else>{{ form.adviserName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="editStatus"
          type="primary"
          size="small"
          icon="Finished"
          @click="submitForm"
          >保存</el-button
        >
        <el-button
          v-else
          type="warning"
          size="small"
          icon="Edit"
          @click="editStatus = true"
          >修改</el-button
        >
        <el-button
          v-if="form.id && editStatus"
          type="info"
          size="small"
          icon="Close"
          @click="handleCancel"
          >取消修改</el-button
        >
        <el-button
          v-if="form.id"
          icon="Refresh"
          type="success"
          size="small"
          @click="getForm"
        >
          刷新</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { getToken } from "@/utils/auth";
import { updateCompany } from "@/api/business/crm/company";
import {
  getStandardCompany,
  addStandardCompany,
  updateStandardCompany,
} from "@/api/business/standardCompany";
import useUserStore from "@/store/modules/user";
import { deepClone } from "@/utils";
import { listUser } from "@/api/system/user";
import {
  incomeDefault,
  taxTypes,
  confirmDefault,
  collectionMethods,
  yesOrNo,
} 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 mainNum = ref(0);
const zero = ref(0);
const provinces = ref(proxy.region.getProvinces());
provinces.value.unshift({ code: "", name: "全部" });
const cities = ref([]);
const districts = 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" }],
    socialCreditCode: [
      { required: true, message: "税号不能为空", trigger: "blur" },
      { max: 18, min: 18, message: "税号为18位", trigger: "blur" },
    ],
    provinceCode: [{ validator: areaValidator, trigger: "blur" }],
    annualIncome: [
      { required: true, message: "年收入不能为空", trigger: "blur" },
    ],
    collectionMethod: [
      { required: true, message: "请选择征收方式", trigger: "blur" },
    ],
    taxType: [{ required: true, message: "纳税性质不能为空", trigger: "blur" }],
  },
});

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 queryRadio = ref("base-form");
const { form, rules, followData } = toRefs(data);
/***********************  表单页方法 ****************************/

/** 抽屉打开 */
function open(id) {
  reset();
  visible.value = true;
  handleSelectProvince();
  if (id) {
    getStandardCompany(id).then((response) => {
      form.value = response.data;
      console.log(response.data);
      editStatus.value = false;
      title.value = "修改客户";
      zero.value = form.value.isZero;
      loading.value = false;
    });
  } else {
    editStatus.value = true;
    title.value = "添加客户";
  }
}

function handleCancel() {
  editStatus.value = false;
  getForm();
}

/** 输入框输出建议 */
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;
}

/**  取消按钮 */
function cancel() {
  visible.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = deepClone(companyEmptyData);
  followData.value = {};
  proxy.resetForm("details");
}
function handleDownLoad(url) {
  window.open(webHost + url);
}

function getForm() {
  loading.value = true;
  getStandardCompany(form.value.id).then((response) => {
    loading.value = false;
    form.value = response.data;
  });
}

/** 提交保存 */
function submitForm() {
  if (zero.value != form.value.isZero && form.value.isZero == 0) {
    proxy.$modal.msgError("非零申报不能转为零申报！");
    return;
  }
  form.value.isZero = zero.value;
  proxy.$refs["details"].validate((valid) => {
    if (valid) {
      if (form.value.id) {
        updateStandardCompany(form.value).then((response) => {
          proxy.$modal.msgSuccess("保存成功!");
          visible.value = false;
          editStatus.value = false;
          getList.value();
        });
      } else {
        addStandardCompany(form.value).then((res) => {
          proxy.$modal.msgSuccess("保存成功!");
          editStatus.value = false;
          getList.value();
        });
      }
    }
  });
}

/** 添加从表 */
function handleAdd() {
  for (var i = 0; i < addDetailNum.value; i++) {
    form.value.members.push({});
  }
}

/** 删除从表 */
function handleDel(index) {
  proxy.$modal
    .confirm("确定删除?")
    .then(() => {
      form.value.members.splice(index, 1);
    })
    .catch(() => {
      proxy.$modal.msg("已取消删除");
    });
}

function handleDelAttach(index) {
  proxy.$modal
    .confirm("确定删除?")
    .then(() => {
      form.value.attaches.splice(index, 1);
    })
    .catch(() => {
      proxy.$modal.msg("已取消删除");
    });
}

/** 单选添加 */
function handleDialogOpen(person) {
  multiple.value = false;
  currentMember.value = person;
  proxy.$refs.personRef.open();
}

/** 多选添加 */
function handleAddBatch() {
  multiple.value = true;
  proxy.$refs.personRef.open();
}

function handleSingleSelected(person) {
  console.log("单选带回", person);
  if (
    form.value.members.findIndex((item) => item.personId === person.id) === -1
  ) {
    currentMember.value.personId = person.id;
    currentMember.value.name = person.name;
    currentMember.value.code = person.code;
    currentMember.value.gender = person.gender;
    currentMember.value.age = person.age;
    currentMember.value.phone = person.phone;
  } else {
    proxy.$modal.msgError(person.name + "已存在,请勿重复添加！");
  }
}

function handleMultipleSelected(selection) {
  console.log("多选回带", selection);
  for (var i = 0; i < selection.length; ++i) {
    const newPerson = {};
    if (
      form.value.members.findIndex(
        (item) => item.personId === selection[i].id
      ) === -1
    ) {
      newPerson.personId = selection[i].id;
      newPerson.name = selection[i].name;
      newPerson.code = selection[i].code;
      newPerson.gender = selection[i].gender;
      newPerson.age = selection[i].age;
      newPerson.phone = selection[i].phone;
      form.value.members.push(newPerson);
    } else {
      proxy.$modal.msgError(selection[i].name + "已存在,请勿重复添加！");
    }
  }
}

function scrollTargetTo(target) {
  const targetElement = document.getElementById(target);
  if (targetElement) {
    targetElement.scrollIntoView();
  }
}

function handleAddContactor() {
  const contactor = JSON.parse(JSON.stringify(contactorEmptyData));
  form.value.contactors.push(contactor);
  return;
}

function areaValidator(rule, value, callback) {
  if (form.value.provinceCode === "") {
    callback(new Error("省份不能为空"));
    return;
  }
  if (form.value.cityCode === "") {
    callback(new Error("城市不能为空"));
    return;
  }
  if (form.value.districtCode === "") {
    callback(new Error("行政区不能为空"));
    return;
  }
  return callback();
}

function handleSelectProvince() {
  const _provinceCode = form.value.provinceCode;
  const _province = provinces.value.find(function (item) {
    return item.code === _provinceCode;
  });
  form.value.province = _province.name;
  cities.value = proxy.region.getCities(_provinceCode);
  if (cities.value.length === 0) {
    // 清空城市数据
    form.value.cityCode = "";
    form.value.city = "";
    cities.value = [];
    // 清空行政区数据
    form.value.districtCode = "";
    form.value.district = "";
    districts.value = [];
  } else {
    cities.value.unshift({ code: "", name: "全部" });
    form.value.cityCode = cities.value[0].code;
    form.value.city = cities.value[0].name;
    handleSelectCity();
  }
}

function handleSelectCity() {
  const _cityCode = form.value.cityCode;
  const _city = cities.value.find(function (item) {
    return item.code === _cityCode;
  });
  form.value.city = _city.name;
  districts.value = proxy.region.getDistricts(_cityCode);
  if (districts.value.length === 0) {
    // 清空行政区数据
    form.value.districtCode = "";
    form.value.district = "";
    districts.value = [];
  } else {
    districts.value.unshift({ code: "", name: "全部" });
    form.value.districtCode = districts.value[0].code;
    form.value.district = districts.value[0].name;
  }
}

function handleSelectDistrict() {
  const _districtCode = form.value.districtCode;
  const _district = districts.value.find(function (item) {
    return item.code === _districtCode;
  });
  form.value.district = _district.name;
}

// 暴露给父组件的方法
defineExpose({
  open,
});
</script>

<style>
.radio-scroll .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  color: rgb(64, 158, 255);
  background-color: rgba(0, 0, 0, 0);
  border-color: rgba(0, 0, 0, 0) rgba(0, 0, 0, 0) rgb(64, 158, 255)
    rgba(0, 0, 0, 0);
  border-style: none none solid none;
  border-width: 0 0 3px 0;
  box-shadow: none;
}

.radio-scroll .el-radio-button__inner {
  border: none;
  background-color: rgba(0, 0, 0, 0);
  border-color: rgba(0, 0, 0, 0);
  border-style: none none solid none;
  border-width: 0 0 3px 0;
  box-shadow: none;
}

.radio-scroll .el-radio-button:first-child .el-radio-button__inner {
  border-left: none;
  border-radius: 0 0 0 0;
}

.radio-scroll .el-radio-button:last-child .el-radio-button__inner {
  border-radius: 0 0 0 0;
}

/* .company-list .detail-head {
  margin-bottom: 10px;
} */
</style>