<script lang="ts" setup name="ListSourceAdd">
/**
 * 添加/编辑/详情客户
 */
import type { Ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { FormInstance } from 'element-plus'
import type { IAdvice, SimpleCompany } from './advice_interface'
import { addAdvice, getAdviceDetail, updateAdvice } from '@/api/customer/advice'
import { SCHEDULE } from '@/utils/scheduleDict'
import type { IAddress } from '@/components/AddressSelect/address-interface'
import { getDictByCode } from '@/api/system/dict'
const loading = ref(false) // 表单加载状态
const infoId = ref('') // id
const pageType = ref('add') // 页面类型: add, edit, detail
const buttonLoading = ref(false) // 按钮加载状态
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}
// 字典
interface dictType {
  id: string
  name: string
  value: string
}
// 从路由中获取页面类型参数
const $route = useRoute()
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
const dataForm: Ref<IAdvice> = ref({
  id: '',
  adviceNo: '', // 投诉编号
  adviceClass: '', // 投诉类型
  adviceType: '', // 投诉类别
  advicePerson: '', // 投诉人-名称
  personPhone: '', // 投诉人联系方式
  customerName: '', // 公司名称
  customerNo: '', //	客户编号
  customerId: '', // 客户id
  content: '', // 投诉内容
  handleStatus: '', // 处置状态
  handleMessage: '', // 处置意见
  adviceTime: '', // 投诉时间
})
const companyInfo: SimpleCompany = reactive({
  customerName: '', // 公司名称
  customerNo: '', //	客户编号
  customerId: '', // 客户id
  grade: '', // 履约评级
  gradeName: '', // 履约评级
  companySize: '', // 公司规模
  companySizeName: '', // 公司规模
  businessSize: '', // 业务规模
  businessSizeName: '', // 业务规模
  evaluation: '', // 整体评价
  evaluationName: '', // 整体评价
})
const ruleFormRef = ref<FormInstance>()

const adviceClassList = ref<dictType[]>([]) // 投诉建议类型
const adviceTypeList = ref<dictType[]>([]) // 投诉建议类别
function getDict() {
  // 获取公司规模
  getDictByCode('adviceClass').then((response) => {
    adviceClassList.value = response.data
  })
  // 获取业务规模
  getDictByCode('adviceType').then((response) => {
    adviceTypeList.value = response.data
  })
}
getDict()

// 校验规则
const rules = ref({
  customerName: [{ required: true, message: '公司名称不能为空', trigger: ['blur', 'change'] }],
  advicePerson: [{ required: true, message: '投诉人不能为空', trigger: ['blur', 'change'] }],
  adviceClass: [{ required: true, message: '投诉/建议类型必选', trigger: ['blur', 'change'] }],
  adviceTime: [{ required: true, message: '投诉/建议时间不能为空', trigger: ['blur', 'change'] }],
  adviceType: [{ required: true, message: '投诉/建议类别必选', trigger: ['blur', 'change'] }],
}) // 表单验证规则
// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
const getInfo = () => {
  loading.value = true
  getAdviceDetail({ id: infoId.value }).then((res) => {
    res.data = {
      id: '1597579843411234817',
      adviceNo: 'ts202201022131', // 投诉编号
      adviceClass: '0', // 投诉类型
      adviceType: '1', // 投诉类别
      advicePerson: '张三', // 投诉人-名称
      personPhone: '87447', // 投诉人联系方式
      customerName: '特别大公司', // 公司名称
      adviceTime: '2022-12-25 23:58:00',
      customerNo: '', //	客户编号
      customerId: '', // 客户id
      content: '没人接电话', // 投诉内容
      handleStatus: '0', // 处置状态-0未处置，1已处置
      handleMessage: '', // 处置意见
    }
    dataForm.value = res.data
    loading.value = false
  })
}

const tempCompanyList = ref<SimpleCompany[]>([
  { customerId: '111', customerNo: '12312456', customerName: '京东', businessSizeName: '0~10万', companySizeName: '小微企业', gradeName: '优质', evaluationName: '重点客户' },
  { customerId: '112', customerNo: '12312451', customerName: '阿里', businessSizeName: '0~10万', companySizeName: '大企业', gradeName: '一般', evaluationName: '重点客户' },
  { customerId: '113', customerNo: '12312452', customerName: '淘宝', businessSizeName: '0~10万', companySizeName: '小微企业', gradeName: '优质', evaluationName: '重点客户' },
  { customerId: '114', customerNo: '12312453', customerName: '天猫', businessSizeName: '0~10万', companySizeName: '小微企业', gradeName: '优质', evaluationName: '重点客户' },
  { customerId: '115', customerNo: '12312454', customerName: '203d', businessSizeName: '0~10万', companySizeName: '小微企业', gradeName: '优质', evaluationName: '重点客户' },
  { customerId: '116', customerNo: '12312456', customerName: '万达', businessSizeName: '0~10万', companySizeName: '小微企业', gradeName: '优质', evaluationName: '重点客户' },
])
// 查询公司列表
const queryCompany = (queryString: string, cb: any) => {
  // TODO: 远程查询符合要求的公司列表
  const results = queryString ? tempCompanyList.value.filter((item) => { item.customerName.includes(queryString) }) : tempCompanyList.value
  cb(results)
}

// 选中
const handleCompanySelect = (select: Record<string, any>) => {
  const item = select as SimpleCompany
  companyInfo.customerName = item.customerName
  companyInfo.customerNo = item.customerNo
  companyInfo.customerId = item.customerId
  companyInfo.gradeName = item.gradeName
  companyInfo.companySizeName = item.companySizeName
  companyInfo.businessSizeName = item.businessSizeName
  companyInfo.evaluationName = item.evaluationName
}
// 打印表单
const printObj = ref({
  id: 'form', // 需要打印元素的id
  popTitle: '投诉/建议详情', // 打印配置页上方的标题
  // extraHead: '<div style="display: flex;flex-direction: column;text-align: center"><h3>投诉/建议详情</h3></div>', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})

// 保存
function saveForm(formEl: FormInstance | undefined) {
  if (!formEl) { return }
  formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (dataForm.value.id) {
          updateAdvice(dataForm.value).then((res) => {
            if (res.code === 200) {
              dataForm.value.id = res.data.id
              dataForm.value.customerNo = res.data.customerNo
              ElMessage.success('已保存')
              $router.go(-1)
            }
          })
        }
        else {
          addAdvice(dataForm.value).then((res) => {
            if (res.code === 200) {
              dataForm.value.id = res.data.id
              dataForm.value.customerNo = res.data.customerNo
              ElMessage.success('已保存')
              $router.go(-1)
            }
          })
        }
      })
    }
  })
}
// 非添加页面获取详情
if (pageType.value !== 'add') {
  getInfo()
}
else {
  dataForm.value.adviceTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
}
</script>

<template>
  <app-container>
    <el-form
      id="form"
      ref="ruleFormRef"
      :model="dataForm"
      :label-width="120"
      label-position="right"
      :rules="rules"
    >
      <detail-page :title="`投诉/建议-${textMap[pageType]}`">
        <template #btns>
          <el-button v-if="pageType === 'detail'" v-print="printObj" type="primary">
            打印
          </el-button>
          <el-button v-if="pageType !== 'detail'" type="primary" @click="saveForm(ruleFormRef)">
            保存
          </el-button>
          <el-button type="info" @click="close">
            关闭
          </el-button>
        </template>
        <div>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="投诉/建议编号" prop="adviceNo">
                <el-input
                  v-model="dataForm.adviceNo"
                  :placeholder="pageType === 'detail' ? '' : '系统自动生成'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="投诉/建议类型" prop="adviceClass">
                <el-select v-model="dataForm.adviceClass" :placeholder="pageType === 'detail' ? '' : '请选择投诉/建议类型'" :disabled="pageType === 'detail'" class="full-width-input">
                  <el-option v-for="item in adviceClassList" :key="item.id" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="投诉人" prop="advicePerson">
                <el-input
                  v-model="dataForm.advicePerson"
                  :placeholder="pageType === 'detail' ? '' : '请输入投诉人'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="投诉人联系方式" prop="personPhone">
                <el-input
                  v-model="dataForm.personPhone"
                  :placeholder="pageType === 'detail' ? '' : '请输入投诉人联系方式'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="投诉/建议时间" prop="adviceTime">
                <el-date-picker
                  v-model="dataForm.adviceTime"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  class="full-width-input"
                  :placeholder="pageType === 'detail' ? '' : '请输入投诉时间'"
                  :disabled="pageType === 'detail'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="投诉/建议类别" prop="adviceType">
                <el-select v-model="dataForm.adviceType" :placeholder="pageType === 'detail' ? '' : '请选择投诉/建议类别'" :disabled="pageType === 'detail'" class="full-width-input">
                  <el-option v-for="item in adviceTypeList" :key="item.id" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="公司名称" prop="customerName">
                <el-autocomplete
                  v-model="dataForm.customerName"
                  :fetch-suggestions="queryCompany"
                  placeholder="请输入公司名称"
                  value-key="customerName"
                  class="full-width-input"
                  :disabled="pageType === 'detail'"
                  @select="handleCompanySelect"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户编号">
                <el-input
                  v-model="companyInfo.customerNo"
                  placeholder=""
                  disabled
                  :class="{ 'detail-input': pageType === 'detail' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="公司规模">
                <el-input
                  v-model="companyInfo.companySizeName"
                  placeholder=""
                  disabled
                  :class="{ 'detail-input': pageType === 'detail' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="业务规模">
                <el-input
                  v-model="companyInfo.businessSizeName"
                  placeholder=""
                  disabled
                  :class="{ 'detail-input': pageType === 'detail' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="履约评级">
                <el-input
                  v-model="companyInfo.gradeName"
                  placeholder=""
                  disabled
                  :class="{ 'detail-input': pageType === 'detail' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="整体评价">
                <el-input
                  v-model="companyInfo.evaluationName"
                  placeholder=""
                  disabled
                  :class="{ 'detail-input': pageType === 'detail' }"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="投诉/建议内容" prop="content">
                <el-input
                  v-model="dataForm.content"
                  :maxlength="250"
                  :rows="4"
                  type="textarea"
                  :placeholder="pageType === 'detail' ? '' : '请输入投诉内容'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </detail-page>
      <detail-block title="处置意见">
        <el-row>
          <el-col :span="24">
            <el-input
              v-model="dataForm.handleMessage"
              :maxlength="250"
              :rows="4"
              type="textarea"
              :placeholder="pageType === 'detail' ? '' : '请输入处置意见'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-col>
        </el-row>
      </detail-block>
    </el-form>
  </app-container>
</template>

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