<template>
  <div class="information pl-4 pr-4 pt-3 pb-3">
    <div class="flex justify-between">
      <div class="title">基本信息</div>
      <div>
        <el-button type="primary" @click="claimCustomer()" v-if="!information.inchargerName"
          >认领</el-button
        >
        <el-button type="primary" @click="transferCli()">转移</el-button>
        <el-button type="primary" v-permission="['customerEdit']" @click="editCustomer()"
          >编辑</el-button
        >
      </div>
    </div>
    <div class="form flex flex-wrap justify-between">
      <div class="formItem flex pt-2 pb-1">
        <div class="w-20 text-right text-gray-500">客户名称：</div>
        <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1" v-ellipsis-tooltip>
          {{ information.customName }}
        </div>
      </div>
      <div class="formItem flex pt-2 pb-1">
        <div class="w-22 text-right text-gray-500">客户来源：</div>
        <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1">
          {{ information.customSourceValue }}
        </div>
      </div>
      <div class="formItem flex pt-2 pb-1">
        <div class="w-22 text-right text-gray-500">电话号码：</div>
        <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1" v-ellipsis-tooltip>
          {{ information.telPhone }}
        </div>
      </div>
      <div class="formItem flex pt-2 pb-1">
        <div class="w-22 text-right text-gray-500">邮箱：</div>
        <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1" v-ellipsis-tooltip>
          {{ information.email }}
        </div>
      </div>
      <div class="formItem flex pt-2 pb-1">
        <div class="w-22 text-right text-gray-500">客户行业：</div>
        <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1">
          {{ information.customerIndustryValue }}
        </div>
      </div>
      <div class="formItem flex pt-2 pb-1">
        <div class="w-22 text-right text-gray-500">客户级别：</div>
        <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1">
          {{ information.customerLevelValue }}
        </div>
      </div>
      <div class="formItem flex pt-2 pb-1">
        <div class="w-22 text-right text-gray-500">客户地址：</div>
        <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1">
          {{ information.address }}
        </div>
      </div>
      <div class="formItem flex pt-2 pb-1">
        <div class="w-22 text-right text-gray-500">负责人：</div>
        <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1">
          {{ information.inchargerName }}
        </div>
      </div>
      <div class="formItem flex pt-2 pb-1">
        <div class="w-22 text-right text-gray-500">创建人：</div>
        <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1">
          {{ information.creatorName }}
        </div>
      </div>
      <div class="formItem flex pt-2 pb-1">
        <div class="w-22 text-right text-gray-500">创建时间：</div>
        <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1">
          {{ information.newCreateTime }}
        </div>
      </div>
      <div class="formItem flex pt-2 pb-1" style="width: 100%">
        <div class="w-22 text-right text-gray-500">备注：</div>
        <div class="flex-1 ml-1 text" v-ellipsis-tooltip>
          {{ information.customDesc }}
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog
      v-model="allVisible.transferCustomerVisible"
      width="600"
      :show-close="false"
      top="10vh"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="flex justify-between items-center border-b pb-3 dialog-header">
          <h4 :id="titleId">{{ '转移客户' }}</h4>
          <div>
            <el-button
              type="primary"
              :loading="allLoading.transferCustomerLoading"
              @click="transferCustomer()"
              >转移</el-button
            >
            <el-button @click="allVisible.transferCustomerVisible = false">取消</el-button>
          </div>
        </div>
      </template>
      <div class="scroll-bar m-6">
        <div class="flex mb-4">
          <div class="w-20 flex items-center justify-end pr-4">转移至:</div>
          <el-select v-model="transferValue" placeholder="请选择" class="flex1">
            <el-option
              v-for="item in transferOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="pl-3 text-[#e94a4a]">转移后，将看不到此客户</div>
      </div>
    </el-dialog>

    <el-dialog v-model="allVisible.editCustomerVisible" width="1000" :show-close="false" top="10vh">
      <template #header="{ close, titleId, titleClass }">
        <div class="flex justify-between items-center border-b pb-3 dialog-header">
          <h4 :id="titleId">{{ '编辑客户' }}</h4>
          <div>
            <el-button type="primary" @click="saveCustomer()" :loading="allLoading.saveLading"
              >保存</el-button
            >
            <el-button @click="closeVisible('editCustomerVisible')">取消</el-button>
          </div>
        </div>
      </template>
      <div
        class="h-[60vh] overflow-y-auto scroll-bar pt-3"
        v-loading="allLoading.generateFormDataLoading"
      >
        <GenerateForm
          ref="generateForm"
          :data="generateFormData"
          :value="generateFormValue"
          :key="generateFormKey"
        />
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { confirmAction } from '@/utils/tools';
import { ref, reactive, onMounted, onUnmounted, defineExpose, inject, watchEffect } from 'vue';
import { GenerateForm } from '@zmjs/form-design';
import { useStore } from '@/store/index';
import { get, post } from '@/utils/request';
import { GETPERSONNEL, URL_CLAIM, URL_EDITSAVE, URL_TEMPLALE } from '../api';
import { formatDate } from '@/utils/times';

const emits = defineEmits(['refreshData']);
const { userInfo } = useStore();
const props = defineProps<{
  data: any;
}>();
const generateFormData = ref({
  config: {},
  list: []
}); // 自定义表单数据
const generateFormValue = ref({});
const generateForm = ref<typeof GenerateForm>();
const generateFormKey = ref(1);
const globalPopup = inject<GlobalPopup>('globalPopup');
const information = ref<any>({});
const transferValue = ref('');
const transferOptions = ref<personnelInterface[]>([]);

const allLoading = reactive({
  editBusinessLoading: false,
  saveLading: false,
  transferCustomerLoading: false,
  saveContactLoading: false,
  generateFormDataLoading: false
});
const allVisible = reactive({
  transferCustomerVisible: false,
  editCustomerVisible: false
});

function saveCustomer() {
  generateForm.value
    ?.getData()
    .then((res: any) => {
      allLoading.saveLading = true;
      let formVal = { ...generateFormValue.value, ...res };
      delete formVal.createTime;
      post(URL_EDITSAVE, { ...formVal })
        .then((_res) => {
          globalPopup?.showSuccess('操作成功');
          closeVisible('editCustomerVisible');
          emits('refreshData');
        })
        .finally(() => {
          allLoading.saveLading = false;
        });
    })
    .catch((_err: any) => {
      console.log(_err);
      globalPopup?.showError('请填写完整');
    });
}

function transferCli() {
  transferValue.value;
  showVisible('transferCustomerVisible');
}

function transferCustomer() {
  const ids = information.value?.id;
  const inchargerId = information.value?.inchargerName ? transferValue.value : userInfo.id;
  if (!inchargerId) {
    globalPopup?.showWarning('请选择转移的人员');
    return;
  }
  allLoading.transferCustomerLoading = true;
  post(URL_CLAIM, { ids, inchargerId })
    .then((res) => {
      if (res.code == 'ok') {
        globalPopup?.showSuccess('操作成功');
        allVisible.transferCustomerVisible = false;
        emits('refreshData');
      }
    })
    .finally(() => {
      allLoading.transferCustomerLoading = false;
    });
}

function claimCustomer() {
  confirmAction(`确定认领【${information.value.customName}】商机吗？`).then(() => {
    transferCustomer();
  });
}

function editCustomer() {
  const {
    id,
    companyPhone,
    customName,
    inchargerId,
    createTime,
    customSourceId,
    customerIndustryId,
    customerLevelId,
    email,
    telPhone,
    customDesc
  } = information.value;
  const formVal = {
    id,
    customName,
    inchargerId,
    customerIndustryId,
    customerLevelId,
    email,
    customSourceId,
    createTime: formatDate(new Date(createTime)),
    telPhone,
    companyPhone,
    customDesc
  };
  generateFormValue.value = formVal;
  allLoading.generateFormDataLoading = true;
  showVisible('editCustomerVisible');
  setTimeout(() => {
    generateForm.value && generateForm.value?.reset();
    generateFormKey.value++;
    allLoading.generateFormDataLoading = false;
  }, 500);
}

function showVisible(type: keyof typeof allVisible) {
  allVisible[type] = true;
}

function closeVisible(type: keyof typeof allVisible) {
  allVisible[type] = false;
}

async function getSystemField() {
  const { data } = await post(GETPERSONNEL, {});
  transferOptions.value = data.map((item: any) => {
    const { id, name, phone, jobNumber } = item;
    return {
      id,
      name,
      phone,
      jobNumber
    };
  });
  const res = await get(URL_TEMPLALE);
  generateFormData.value = JSON.parse(res.data[0].config);
}

watchEffect(() => {
  const { data } = props;
  information.value = data;
});

// 生命周期钩子
onMounted(() => {
  getSystemField();
});
</script>
<style scoped lang="scss">
.information {
  .title {
    font-size: 18px;
    color: #000;
  }

  .form {
    .formItem {
      width: 48%;
    }

    .text {
      display: -webkit-box;
      /* Safari */
      -webkit-line-clamp: 2;
      /* number of lines to show */
      -webkit-box-orient: vertical;
      overflow: hidden;
      line-height: 1.5;
    }
  }
}
</style>
