<template>
  <div class="tenant">
    <!-- <Banner /> -->
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
          //element talbe事件都能传
          select: select,
        }"
        :action-list="[
          {
            text: '添加联系人',
            action: () => openModal('add'),
          },
        ]"
        @get-list="getList"
      >
        <template #phoneNumber="{ item }">
          {{ item.phoneNumber }}
          <!-- <div>
            <span v-for="(x, index) in getTypeData(item, 0)">
              {{ x.contactNumber }}
              <span v-if="index < getTypeData(item, 0).length - 1">,</span>
            </span>
          </div> -->
        </template>
        <template #email="{ item }">
          <div>
            <span v-for="(x, index) in getTypeData(item, 1)">
              {{ x.contactNumber }}
              <span v-if="index < getTypeData(item, 1).length - 1">,</span>
            </span>
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      :title="modalType == 'add' ? '添加联系人' : '编辑联系人'"
      v-model="dialogVisible"
      width="800"
      v-loading="loading"
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #enterpriseSlot>
          <div style="width: 100%">
            <el-select
              filterable
              allow-create
              v-model="formData.data.enterpriseId"
              :disabled="modalType !== 'add'"
            >
              <el-option
                v-for="item in enterpriseData"
                :label="item.enterpriseName"
                :value="item.enterpriseId"
              >
              </el-option>
            </el-select>
          </div>
        </template>
        <template #fileSlot>
          <div style="width: 100%">
            <el-button type="primary" @click="addRow"> 添加 </el-button>
            <el-form
              ref="tableForm"
              :model="formData.data"
              :rules="rules"
              label-width="0px"
              style="margin-top: 15px"
            >
              <el-table
                :data="formData.data.contactsList"
                v-if="modalType == 'add'"
              >
                <el-table-column
                  prop="contactName"
                  label="联系人"
                  min-width="150"
                >
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="'contactsList.' + $index + '.contactName'"
                      :rules="rules.contactName"
                      :inline-message="true"
                    >
                      <el-input
                        v-model="row.contactName"
                        placeholder="请输入"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="phoneNumber"
                  label="手机号"
                  min-width="150"
                >
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="'contactsList.' + $index + '.phoneNumber'"
                      :rules="rules.phoneNumber"
                      :inline-message="true"
                    >
                      <el-input
                        v-model="row.phoneNumber"
                        placeholder="请输入"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column prop="zip" label="操作" width="100">
                  <template #default="{ $index }">
                    <el-button type="primary" link @click="handleRemove($index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>

              <el-table
                :data="formData.data.externalAddressBookList"
                v-if="modalType == 'edit'"
              >
                <el-table-column prop="type" label="类型" min-width="150">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="'internalAddressBookList.' + $index + '.type'"
                      :inline-message="true"
                    >
                      <!-- :rules="rules.type" -->
                      <el-select v-model="row.type" placeholder="请选择">
                        <el-option
                          v-for="item in contactInformationType"
                          :label="item.dictValue"
                          :value="item.dictKey"
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="contactNumber"
                  label="联系号码"
                  min-width="150"
                >
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="
                        'internalAddressBookList.' + $index + '.contactNumber'
                      "
                      :inline-message="true"
                    >
                      <!-- :rules="rules.contactNumber" -->
                      <el-input
                        v-model="row.contactNumber"
                        placeholder="请输入"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column prop="zip" label="操作" width="100">
                  <template #default="{ $index }">
                    <el-button type="primary" link @click="handleRemove($index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('byform')"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import FileUpload from "@/components/FileUpload/index";
import { computed, defineComponent, ref } from "vue";
import { getToken } from "@/utils/auth";
import useUserStore from "@/store/modules/user";

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const uploadData = ref({});
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");
let fileList = ref([]);
let rules = ref({
  enterpriseId: [
    { required: true, message: "请选择/输入企业", trigger: ["change", "blur"] },
  ],
  contactName: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  phoneNumber: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
  type: [{ required: true, message: "请选择联系类型", trigger: "change" }],
  contactNumber: [
    { required: true, message: "请输入联系号码", trigger: "blur" },
  ],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "来源",
    prop: "enterpriseType",
    data: [
      {
        label: "客户",
        value: "1",
      },
      {
        label: "供应商",
        value: "2",
      },
      {
        label: "自定义",
        value: "3",
      },
    ],
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "来源",
        prop: "enterpriseType",
      },
      render(enterpriseType) {
        return enterpriseType === 1
          ? "客户"
          : enterpriseType === 2
          ? "供应商"
          : enterpriseType === 3
          ? "自定义"
          : "";
      },
    },
    {
      attrs: {
        label: "关联企业",
        prop: "enterpriseName",
      },
    },
    {
      attrs: {
        label: "联系人",
        prop: "contactName",
      },
    },
    {
      attrs: {
        type: "slot",
        slot: "phoneNumber",
        label: "手机号",
      },
    },
    {
      attrs: {
        type: "slot",
        slot: "email",
        label: "电子邮箱",
      },
    },
    // {
    //   attrs: {
    //     label: "座机",
    //     prop: "createTime",
    //   },
    // },
    // {
    //   attrs: {
    //     label: "WhatsApp",
    //     prop: "createTime",
    //   },
    // },

    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "修改",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
            },
            el: "button",
            click() {
              // 弹窗提示是否删除
              ElMessageBox.confirm(
                "此操作将永久删除该数据, 是否继续?",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }
              ).then(() => {
                // 删除
                proxy
                  .post("/contacts/delete", {
                    id: row.id,
                  })
                  .then((res) => {
                    ElMessage({
                      message: "删除成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {
    type: "1",
  },
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const formConfig = ref([]);

const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/contacts/page", sourceList.value.pagination).then((message) => {
    console.log(message);
    sourceList.value.data = message.rows;
    sourceList.value.pagination.total = message.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
const openModal = () => {
  dialogVisible.value = true;
  formConfig.value = configData[0];
  modalType.value = "add";
  formData.data = {
    contactsList: [],
  };
};

const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    if (modalType.value === "add") {
      if (formData.data.contactsList.length > 0) {
        proxy.$refs.tableForm.validate((vaild) => {
          if (vaild) {
            const current = enterpriseData.value.find(
              (x) => x.enterpriseId === formData.data.enterpriseId
            );
            if (current && current !== undefined) {
              formData.data.enterpriseType = current.enterpriseType;
            } else {
              formData.data.enterpriseType = 3;
              formData.data.enterpriseName = formData.data.enterpriseId;
              formData.data.enterpriseId = "";
            }
            submitLoading.value = true;
            proxy.post("/contacts/" + modalType.value, formData.data).then(
              (res) => {
                ElMessage({
                  message: modalType.value == "add" ? "添加成功" : "编辑成功",
                  type: "success",
                });
                dialogVisible.value = false;
                submitLoading.value = false;
                getList();
              },
              (err) => {
                submitLoading.value = false;
              }
            );
          }
        });
      } else {
        return ElMessage({
          message: "请添加联系人！",
          type: "info",
        });
      }
    } else {
      if (formData.data.externalAddressBookList.length > 0) {
        proxy.$refs.tableForm.validate((vaild) => {
          if (vaild) {
            submitLoading.value = true;
            proxy.post("/contacts/" + modalType.value, formData.data).then(
              (res) => {
                const submitData = {
                  contactsId: formData.data.id,
                  externalAddressBookList:
                    formData.data.externalAddressBookList.map((x) => ({
                      ...x,
                    })),
                };
                proxy
                  .post("/externalAddressBook/" + modalType.value, submitData)
                  .then((res) => {
                    ElMessage({
                      message: "编辑成功",
                      type: "success",
                    });
                    dialogVisible.value = false;
                    submitLoading.value = false;
                    getList();
                  });
              },
              (err) => {
                submitLoading.value = false;
              }
            );
          }
        });
      } else {
        return ElMessage({
          message: "请添加联系方式！",
          type: "info",
        });
      }
    }
  });
};

const configData = [
  [
    {
      type: "slot",
      slotName: "enterpriseSlot",
      prop: "enterpriseId",
      label: "关联企业",
    },
    {
      type: "slot",
      slotName: "fileSlot",
      label: "联系方式",
    },
  ],
  [
    {
      type: "slot",
      slotName: "enterpriseSlot",
      prop: "enterpriseId",
      label: "关联企业",
    },
    {
      prop: "contactName",
      type: "input",
      label: "联系人",
    },
    {
      type: "slot",
      slotName: "fileSlot",
      label: "联系方式",
    },
  ],
];

const enterpriseData = ref([]);

const contactInformationType = ref([]);
const getDict = () => {
  const tenantId = useUserStore().user.tenantId;
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      tenantId: tenantId,
      dictCode: "contact_information",
    })
    .then((res) => {
      contactInformationType.value = res.rows;
    });

  proxy.post("/contacts/list", { pageNum: 1, pageSize: 9999 }).then((res) => {
    enterpriseData.value = res;
  });
};

const getDtl = (row) => {
  modalType.value = "edit";
  formConfig.value = configData[1];
  dialogVisible.value = true;
  proxy.post("/contacts/detail", { id: row.id }).then((res) => {
    formData.data = res;
    proxy.post("/externalAddressBook/detail", { id: row.id }).then((res) => {
      formData.data.externalAddressBookList =
        res.map((x) => ({
          id: x.id,
          type: x.type + "",
          contactNumber: x.contactNumber,
        })) || [];
    });
  });
};

const handleRemove = (index) => {
  if (modalType.value === "add") {
    formData.data.contactsList.splice(index, 1);
  } else {
    formData.data.externalAddressBookList.splice(index, 1);
  }
};

getList();
getDict();

const addRow = () => {
  if (modalType.value === "add") {
    formData.data.contactsList.push({
      contactName: "",
      phoneNumber: "",
    });
  } else {
    formData.data.externalAddressBookList.push({
      id: "",
      type: "",
      contactNumber: "",
    });
  }
};

const getTypeData = (item, type) => {
  if (item.internalAddressBookList)
    return item.internalAddressBookList.filter((x) => x.type === type) || [];
};
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>