<template>
  <div>
    <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit" v-loading="loading">
      <template #name>
        <div style="width: 100%">
          <el-autocomplete v-model="formData.data.name" :fetch-suggestions="querySearch" clearable placeholder="请输入" style="width:100%" />
        </div>
      </template>
      <template #allAddress>
        <el-row style="width: 100%">
          <el-col :span="8">
            <el-form-item prop="countryId" class="wid100">
              <el-select v-model="formData.data.countryId" placeholder="国家" filterable style="width:100%"
                         @change="(val) => getCityData(val, '20', true)">
                <el-option v-for="item in countryData" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="provinceName" class="wid100">
              <selectCity placeholder="省/洲" @change="(val) => getCityData(val, '30', true)" style="width:100%" addressId="provinceId"
                          addressName="provinceName" v-model="formData.data" :data="provinceData">
              </selectCity>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="cityName" class="wid100">
              <selectCity placeholder="城市" addressId="cityId" addressName="cityName" style="width:100%" v-model="formData.data" :data="cityData">
              </selectCity>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style=" width: 100%">
          <el-col :span="24">
            <el-form-item prop="address" class="margin-b-0 wid100">
              <el-input v-model="formData.data.address" type="textarea" placeholder="详细地址">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #person>
        <div style="width: 100%">
          <el-button type="primary" @click="clickAddPerson">添 加</el-button>
          <el-table :data="formData.data.customerUserList" style="width: 100%; margin-top: 16px">
            <el-table-column label="联系人" width="160">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'customerUserList.' + $index + '.name'" class="margin-b-0 wid100" :rules="rules.name2" :inline-message="true">
                    <el-input v-model="row.name" placeholder="请输入联系人" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="电子邮箱">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'customerUserList.' + $index + '.email'" class="margin-b-0 wid100" :rules="rules.email" :inline-message="true">
                    <el-input v-model="row.email" placeholder="请输入电子邮箱" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="120" fixed="right">
              <template #default="{ row, $index }">
                <el-button type="primary" link @click="clickInformationMore(row, $index)">更多</el-button>
                <el-button type="primary" link @click="clickDelete($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </byForm>

    <el-dialog title="更多联系方式" v-if="openPerson" v-model="openPerson" width="700">
      <el-form :label-position="'right'" :model="formPerson.data" :rules="rulesPerson" ref="person" label-width="100px">
        <el-form-item label="联系人" prop="name">
          <el-input v-model="formPerson.data.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="formPerson.data.email" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="更多联系方式">
          <div style="width: 100%">
            <el-button type="primary" @click="clickAddMoreInformation">添 加</el-button>
            <el-table :data="formPerson.data.contact" style="width: 100%; margin-top: 16px">
              <el-table-column label="类型" width="180">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    <el-form-item :prop="'contact.' + $index + '.type'" class="margin-b-0 wid100" :rules="rulesPerson.type" :inline-message="true">
                      <el-select v-model="row.type" placeholder="请选择类型" style="width: 100%">
                        <el-option v-for="item in contactType" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="联系号码">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    <el-form-item :prop="'contact.' + $index + '.contactNo'" class="margin-b-0 wid100" :rules="rulesPerson.contactNo"
                                  :inline-message="true">
                      <el-input v-model="row.contactNo" placeholder="请输入联系号码" />
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="120" fixed="right">
                <template #default="{ $index }">
                  <el-button type="primary" link @click="clickInformationDelete($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="openPerson = false" size="default">取 消</el-button>
        <el-button type="primary" @click="submitPerson()" size="default">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";
import selectCity from "@/components/selectCity/index.vue";
const props = defineProps({
  modalType: String,
  customerId: String,
  customerMail: {
    type: String,
    default: "",
  },
  isPrivate: {
    type: Boolean,
    default: false,
  },
  isHighseas: {
    type: Boolean,
    default: false,
  },
});
const modalType = ref("add");
const isHighseas = ref(false);
isHighseas.value = props.isHighseas;
const customerId = ref("");
const { proxy } = getCurrentInstance();
const loading = ref(false);
const customerTag = ref([]);
const customerSource = ref([]);
const customerStatus = ref([]);
const contactType = ref([]);
const userList = ref([]);
const submit = ref(null);
const formData = reactive({
  data: {
    countryId: "44",
  },
});
const getDict = () => {
  proxy
    .getDictOne([
      "customer_tag",
      "customer_source",
      "customer_status",
      "contact_type",
    ])
    .then((res) => {
      customerTag.value = res["customer_tag"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      customerSource.value = res["customer_source"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      console.log(res, "ss");
      customerStatus.value = res["customer_status"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      contactType.value = res["contact_type"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    });
  proxy
    .get("/tenantUser/list", {
      pageNum: 1,
      pageSize: 10000,
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      userList.value = res.rows.map((item) => {
        return {
          label: item.nickName,
          value: item.userId,
        };
      });
    });
};
getDict();
const countryData = ref([]);
const provinceData = ref([]);
const cityData = ref([]);
const getCityData = (id, type, isChange = false) => {
  proxy.post("/customizeArea/list", { parentId: id }).then((res) => {
    if (type === "20") {
      provinceData.value = res;
      if (isChange) {
        formData.data.provinceId = "";
        formData.data.provinceName = "";
        formData.data.cityId = "";
        formData.data.cityName = "";
      }
    } else if (type === "30") {
      cityData.value = res;
      if (isChange) {
        formData.data.cityId = "";
        formData.data.cityName = "";
      }
    } else {
      countryData.value = res;
    }
  });
};
getCityData("0");
const getDtl = () => {
  loading.value = true;
  proxy.post("/customer/detail", { id: customerId.value }).then((res) => {
    if (res.tag) {
      res.tags = res.tag.split(",");
    } else {
      res.tags = [];
    }
    formData.data = res;
    getCityData(formData.data.countryId, "20");
    if (formData.data.provinceId) {
      getCityData(formData.data.provinceId, "30");
    }
    loading.value = false;
  });
};
if (props && props.modalType) {
  modalType.value = props.modalType;
  if (modalType.value == "add") {
    formData.data = {
      countryId: "44",
      tags: [],
      customerUserList: [
        {
          name: "",
          email: "",
        },
      ],
    };
    if (props.customerMail) {
      formData.data.customerUserList[0].email = props.customerMail;
    }
    getCityData(formData.data.countryId, "20");
  } else if (modalType.value == "edit" && props.customerId) {
    customerId.value = props.customerId;
    getDtl();
  }
}

const formOption = reactive({
  inline: true,
  labelWidth: 190,
  itemWidth: 100,
  rules: [],
});
const formConfig = computed(() => {
  return [
    // {
    //   type: "input",
    //   prop: "name",
    //   label: "客户名称",
    //   required: true,
    //   itemWidth: 100,
    //   itemType: "text",
    // },
    {
      type: "title1",
      title: "基本信息",
    },
    {
      type: "slot",
      slotName: "name",
      prop: "name",
      label: "客户名称",
    },
    {
      type: "slot",
      slotName: "allAddress",
      label: "详细地址",
    },
    {
      type: "select",
      label: "客户来源",
      prop: "source",
      itemWidth: 50,
      data: customerSource.value,
    },
    {
      type: "select",
      label: "客户类型",
      prop: "status",
      itemWidth: 50,
      data: customerStatus.value,
    },
    {
      type: "select",
      label: "业务员",
      prop: "userId",
      itemWidth: 100,
      data: userList.value,
      clearable: true,
      disabled: isHighseas.value,
    },
    {
      type: "select",
      label: "客户标签",
      prop: "tags",
      itemWidth: 100,
      multiple: true,
      data: customerTag.value,
      style: {
        width: "100%",
      },
    },
    {
      type: "input",
      prop: "beneficiaryName",
      label: "Beneficiary Name",
      required: true,
      itemWidth: 50,
      itemType: "text",
    },
    {
      type: "input",
      prop: "beneficiaryAccountNumber",
      label: "Beneficiary Account Number",
      required: true,
      itemWidth: 50,
      itemType: "text",
    },
    {
      type: "input",
      prop: "beneficiaryBank",
      label: "Beneficiary Bank",
      required: true,
      itemWidth: 50,
      itemType: "text",
    },
    {
      type: "input",
      prop: "swiftCode",
      label: "Swift Code",
      required: true,
      itemWidth: 50,
      itemType: "text",
    },
    {
      type: "input",
      prop: "beneficiaryBankAddress",
      label: "Beneficiary Bank Address",
      required: true,
      itemWidth: 50,
      itemType: "text",
    },
    {
      type: "input",
      prop: "beneficiaryAddress",
      label: "Beneficiary Address",
      required: true,
      itemWidth: 50,
      itemType: "text",
    },
    {
      type: "title1",
      title: "联系人",
    },
    {
      type: "slot",
      slotName: "person",
      label: "客户联系人",
    },
  ];
});

const rules = ref({
  name: [{ required: true, message: "请输入客户名称", trigger: "blur" }],
  name2: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  email: [{ required: true, message: "请输入电子邮箱", trigger: "blur" }],
  countryId: [{ required: true, message: "请选择国家", trigger: "change" }],
  source: [{ required: true, message: "请选择客户来源", trigger: "change" }],
  status: [{ required: true, message: "请选择类型", trigger: "change" }],
});
if (props.isPrivate) {
  rules.value.userId = [
    { required: true, message: "请选择业务员", trigger: "change" },
  ];
}
const clickAddPerson = () => {
  if (
    formData.data.customerUserList &&
    formData.data.customerUserList.length > 0
  ) {
    formData.data.customerUserList.push({
      name: "",
      email: "",
    });
  } else {
    formData.data.customerUserList = [
      {
        name: "",
        email: "",
      },
    ];
  }
};
const formPerson = reactive({
  data: {},
});
const rulesPerson = ref({
  name: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  email: [{ required: true, message: "请输入电子邮箱", trigger: "blur" }],
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  contactNo: [{ required: true, message: "请输入联系号码", trigger: "blur" }],
});
const person = ref(null);
const openPerson = ref(false);
const moreIndex = ref(0);
const clickInformationMore = (item, index) => {
  moreIndex.value = index;
  if (item.contactJson) {
    item.contact = JSON.parse(item.contactJson);
  } else {
    item.contact = [];
  }
  formPerson.data = proxy.deepClone(item);
  openPerson.value = true;
};
const clickDelete = (index) => {
  formData.data.customerUserList.splice(index, 1);
};
const clickAddMoreInformation = () => {
  if (formPerson.data.contact && formPerson.data.contact.length > 0) {
    formPerson.data.contact.push({
      type: "",
      contactNo: "",
    });
  } else {
    formPerson.data.contact = [
      {
        type: "",
        contactNo: "",
      },
    ];
  }
};
const clickInformationDelete = (index) => {
  formPerson.data.contact.splice(index, 1);
};
const submitPerson = () => {
  person.value.validate((valid) => {
    if (valid) {
      formPerson.data.contactJson = JSON.stringify(formPerson.data.contact);
      formData.data.customerUserList[moreIndex.value] = formPerson.data;
      openPerson.value = false;
    }
  });
};

const handleSubmit = () => {
  submit.value.handleSubmit(() => {
    if (
      formData.data.customerUserList &&
      formData.data.customerUserList.length > 0
    ) {
      formData.data.tag = formData.data.tags.join(",");
      loading.value = true;
      proxy.post("/customer/" + modalType.value, formData.data).then(
        () => {
          ElMessage({
            message: modalType.value == "add" ? "添加成功" : "编辑成功",
            type: "success",
          });
          proxy.$emit("refreshList");
          loading.value = false;
        },
        (err) => {
          console.log(err);
          loading.value = false;
        }
      );
    } else {
      ElMessage("请添加客户联系人");
    }
  });
};
const querySearch = (queryString, callback) => {
  proxy
    .post("/customer/page", {
      pageNum: 1,
      pageSize: 20,
      name: queryString,
    })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        res.rows = res.rows.map((item) => {
          return {
            ...item,
            value: item.name,
          };
        });
        callback(res.rows);
      } else {
        callback([]);
      }
    });
};

defineExpose({
  handleSubmit,
});
</script>

<style lang="scss" scoped>
</style>