<template>
  <div class="content" v-loading="loading">
    <div class="line">
      <span class="title_" v-if="detailsData.customerCode">客户代码：{{ detailsData.customerCode }}</span>
      <span class="title_" v-if="detailsData.customerCode && detailsData.status" style="margin: 0 6px">|</span>
      <span class="title_" v-if="detailsData.status">客户类型：{{ dictValueLabel(detailsData.status, customerStatus) }}</span>
    </div>
    <div class="line" v-if="detailsData.source">
      <span class="title_">客户来源：</span>
      <span>{{ dictValueLabel(detailsData.source, customerSource) }}</span>
    </div>
    <div class="line">
      <span class="title_">地址：</span>
      <span
        >{{ detailsData.countryName }} , {{ detailsData.provinceName }} ,
        {{ detailsData.cityName }}
        <span v-show="detailsData.address"> , {{ detailsData.address }}</span>
      </span>
    </div>
    <div class="contacts" v-if="detailsData.customerUserList.length > 0">
      <div style="display: flex; justify-content: space-between">
        <span> 相关联系人： </span>
        <el-button type="primary" size="small" style="padding: 0px" text @click="handleAddUserList(detailsData)">添加</el-button>
      </div>
      <div>
        <div v-for="(item, index) in detailsData.customerUserList" :key="index" class="item" v-show="!(index > 1)">
          <div class="img">
            <i class="iconfont icon-iconm_kehd" style="font-size: 26px; color: #cccccc; margin-top: 2px"></i>
          </div>
          <div class="details">
            <div>
              <span> {{ item.name }} </span>
            </div>
            <div class="information">
              <div class="first"><span class="val">Tel：</span>{{ getPhone(item) }}</div>
              <div style="display: flex; justify-content: space-between; height: 20px; line-height: 20px">
                <span class="val" style="flex: 1">Email：</span>{{ item.email }}
                <img
                  src="@/assets/images/portrait/icon_email.png"
                  alt=""
                  style="cursor: pointer; margin-left: 10px; transform: translateY(-1px)"
                  @click="handleSendEmail(item)"
                  v-show="item.email" />
              </div>
            </div>
          </div>
        </div>
        <div style="float: right" v-if="detailsData.customerUserList && detailsData.customerUserList.length > 1">
          <el-button type="primary" link size="small">更多联系人</el-button>
        </div>
      </div>
    </div>

    <el-dialog :title="'添加联系人'" v-if="dialogVisible" v-model="dialogVisible" width="800" v-loading="loadingOperation">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <template #person>
          <div style="width: 100%">
            <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'" :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'" :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>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large" :loading="submitLoading">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="更多联系方式" v-if="openPerson" v-model="openPerson" width="700">
      <el-form :label-position="'top'" :model="formPerson.data" :rules="rulesPerson" ref="person">
        <el-form-item label="联系人" prop="name">
          <el-input v-model="formPerson.data.name" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="formPerson.data.email" />
        </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'" :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'" :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="large">取 消</el-button>
        <el-button type="primary" @click="submitPerson()" size="large">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import byForm from "@/components/byForm/index";
const props = defineProps({
  customerId: {
    type: String,
  },
});
const { proxy } = getCurrentInstance();
const loading = ref(false);
const submitLoading = ref(false);
let detailsData = ref({
  customerUserList: [],
});
let formData = reactive({
  data: {},
});
let formPerson = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
let 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" }],
  provinceId: [{ required: true, message: "请选择省/州", trigger: "change" }],
  cityId: [{ required: true, message: "请选择城市", trigger: "change" }],
  source: [{ required: true, message: "请选择客户来源", trigger: "change" }],
  status: [{ required: true, message: "请选择类型", trigger: "change" }],
});
let 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 formConfig = computed(() => {
  return [
    {
      type: "slot",
      slotName: "person",
      label: "客户联系人",
    },
  ];
});
const dialogVisible = ref(false);
const openPerson = ref(false);
const getData = () => {
  loading.value = true;
  proxy.post("/customer/detail", { id: props.customerId }).then((res) => {
    detailsData.value = res;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
const customerSource = ref([]);
const customerStatus = ref([]);
const contactType = ref([]);
const getDict = () => {
  proxy.getDictOne(["customer_source", "customer_status", "contact_type"]).then((res) => {
    customerSource.value = res["customer_source"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    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,
    }));
  });
};
getDict();
onMounted(() => {
  if (props.customerId) {
    getData();
  }
});

const handleSendEmail = (item) => {
  proxy.$router.push({
    path: "/connect/E-mail/mail",
    query: {
      mail: item.email,
    },
  });
};
const handleAddUserList = (res) => {
  formData.data.customerUserList = [
    {
      name: "",
      email: "",
    },
  ];
  dialogVisible.value = true;
};
const moreIndex = ref(-1);
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 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 person = ref(null);
const submit = ref(null);
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 submitForm = () => {
  submit.value.handleSubmit(() => {
    if (formData.data.customerUserList && formData.data.customerUserList.length > 0) {
      submitLoading.value = true;
      const data = {
        customerId: detailsData.value.id,
        ...formData.data.customerUserList[0],
      };
      proxy.post("/customerUser/add", data).then(
        () => {
          ElMessage({
            message: "添加成功",
            type: "success",
          });
          dialogVisible.value = false;
          getData();
        },
        (err) => {
          submitLoading.value = false;
        }
      );
    } else {
      ElMessage("请添加客户联系人");
    }
  });
};
const getPhone = (res) => {
  if (res.contactJson) {
    let contactJson = JSON.parse(res.contactJson);
    if (contactJson && contactJson.length > 0) {
      return contactJson[0].contactNo;
    }
  }
};
</script>

<style lang="scss" scoped>
.content {
  font-size: 12px;
  padding: 10px;
  .company {
    margin-bottom: 10px;
  }
  .company-name {
    font-weight: 600;
    font-size: 13px;

    color: #333333;
  }
  .contacts {
    margin-top: 15px;
    .item {
      padding: 10px;
      display: flex;
      margin: 6px 0px;
      border: 1px dashed #dddddd;
      .img {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: #eeeeee;
        text-align: center;
        line-height: 40px;
      }
      .details {
        margin-left: 10px;
        display: flex;
        flex: 1;
        flex-direction: column;
        justify-content: space-between;
        .information {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          .first {
            margin-right: 10px;
            height: 20px;
            line-height: 20px;
          }
          .val {
            color: #999999;
          }
        }
      }
    }
    .more {
      text-align: right;
    }
  }
}
.title_ {
  color: #999999;
}
.line {
  margin-bottom: 6px;
}
.img {
  // width: 15px;
  // height: 15px;
  // object-fit: contain;
  cursor: pointer;
}
::v-deep(.el-button--small) {
  --el-button-size: 20px;
}
</style>
