<template>
  <BasicModal v-bind="$attrs" :width="960" @ok="handleOk" @register="registerModal">

    <!-- <template v-if="!ifUpdate" #title>
      <span>新增线索</span>
    </template> -->

    <div v-if="ifUpdate">
      <Result title="请将模板Excel文件导入" v-if="tableListRef.length == 0">
        <template #icon>
          <Icon icon="ant-design:cloud-upload-outlined" size="150px" color="#d6d6d6"/>
        </template>
        <template #extra>
          <ImpExcel @success="loadDataSuccess" dateFormat="YYYY-MM-DD">
            <Button>导入Excel</Button>
          </ImpExcel>
          <Button type="link" style="margin-top: 16px;" @click="exportExcel">下载线索导入模板</Button>
        </template>
      </Result>
      <BasicTable v-for="(table, index) in tableListRef"
        :key="index"
        :columns="table.columns"
        :canResize="false"
        :dataSource="table.dataSource"
        :pagination="{ pageSize: 10 }"
      />
    </div>

    <div class="flex-col" v-else>
      <Tabs tab-position="left" v-model:activeKey="activeKey2" :animated="false" @change="onInfoChange">
        <TabPane key="1" tab="个人资料">
          <BasicForm @register="registerForm" style="padding: 16px 48px 0px 0px;" >
            <!-- <template #birthYear="{ model, field }">
              <DatePicker v-model:value="model[field]" mode="year" :open="open" format="YYYY" @openChange="openChange" @panelChange="panelChange"/>
            </template> -->
            <template #profilePhoto="{ model, field }">
              <CropperAvatar :value="model[field]" @change="uploadAvatarAfter"/>
            </template>
          </BasicForm>
        </TabPane>
        <TabPane key="2" tab="择偶要求">
          <BasicForm @register="registerForm3" style="padding: 16px 48px 0px 0px;">
            <template #age="{ model }">
              <div class="flex-row-center-start">
                <InputNumber placeholder="请输入" :min="0" v-model:value="model['minAge']" />
                <span style="margin: 0 5px">-</span>
                <InputNumber placeholder="请输入" :min="0" v-model:value="model['maxAge']" />
              </div>
            </template>
            <template #height="{ model }">
              <div class="flex-row-center-start">
                <InputNumber placeholder="请输入" :min="0" v-model:value="model['minHeight']" />
                <span style="margin: 0 5px">-</span>
                <InputNumber placeholder="请输入" :min="0" v-model:value="model['maxHeight']" />
              </div>
            </template>
            <template #income="{ model }">
              <div class="flex-row-center-start">
                <InputNumber placeholder="请输入" :min="0" v-model:value="model['minimumIncome']" />
                <span style="margin: 0 5px">-</span>
                <InputNumber placeholder="请输入" :min="0" v-model:value="model['maximumIncome']" />
              </div>
            </template>
          </BasicForm>
        </TabPane>
        <TabPane key="3" tab="线索影像">
          <div style="padding: 16px;">
            <OssUpload v-model="uploadList" @remove="onUploadRemove" :multiple="true" :if-custom-render="true" />
          </div>
        </TabPane>
      </Tabs>
    </div>

    <template v-if="ifUpdate" #footer>
      <div class="flex-row-center-space">
        <ImpExcel @success="loadDataSuccess" dateFormat="YYYY-MM-DD">
          <Button type="primary">导入Excel</Button>
        </ImpExcel>
        <div class="flex-row-center-start">
          <Button @click="close">取消</Button>
          <Button type="primary" @click="handleOk">确定</Button>
        </div>
      </div>
    </template>
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, unref, nextTick } from 'vue'
  import moment from 'moment/moment'
  import dayjs, { Dayjs } from 'dayjs'
  import { Tabs, TabPane, Button, Result, InputNumber, DatePicker } from 'ant-design-vue'
  import Icon from '/@/components/Icon'
  import { downloadByUrl } from '/@/utils/file/download'
  import { OssUpload } from '/@/components/OssUpload'
  import { modalFormSchema, basicInfoData, demandMarriageSchema, demandMarriageMoreData } from './data'
  import { ImpExcel, ExcelData } from '/@/components/Excel';
  import { BasicTable, BasicColumn } from '/@/components/Table'
  import { useMessage } from '/@/hooks/web/useMessage'
  import { BasicForm, useForm } from '/@/components/Form'
  import { BasicModal, useModalInner } from '/@/components/Modal'
  import { CropperAvatar } from '/@/components/Cropper';
  import { createClueRecord, importClueRecord, getClueInfo, editClueRecord } from '/@/api/clue'
  import { formatToDate } from '/@/utils/dateUtil'

  const activeKey2 = ref<string>('1')
  const uploadList = ref<any>([])
  const [registerForm, { setFieldsValue, resetFields, validate, getFieldsValue }] =
    useForm({
      labelWidth: 108,
      schemas: modalFormSchema,
      baseColProps: { span: 22 },
      showActionButtonGroup: false,
    })

  const ifUpdate = ref<boolean>(false)
  const open = ref<boolean>(false)
  const details = ref<any>()
  const [registerModal, { closeModal, setModalProps }] = useModalInner(async (data) => {
    ifUpdate.value = !!data.ifUpdate
    const { record } = data
    var title :string = ''
    if(ifUpdate.value){
      title = '导入线索'
      tableListRef.value = [];
    } else if(record && record.id){
      title = '编辑线索'
      details.value = await getClueInfo(`${record.id}`)
      const { domicilePlaceProvinceCode, domicilePlaceCityCode } = details.value || {}
      const domicilePlace = domicilePlaceCityCode && domicilePlaceProvinceCode ? [domicilePlaceProvinceCode, domicilePlaceCityCode] : []
      const { provinceCode, cityCode, districtCode } = details.value || {}
      const address = provinceCode && cityCode && districtCode ? [provinceCode, cityCode, districtCode] : []
      await nextTick()
      await setFieldsValue({ ...details.value, domicilePlace, address })
      if(details.value.datingClueImageList && details.value.datingClueImageList.length){
        uploadList.value = details.value.datingClueImageList.map((item: string) => {
          return {url: item}
        })
      } else{
        uploadList.value = []
      }
      activeKey2.value = '1'
    } else {
      title = '新增线索'
      details.value = {}
      uploadList.value = []
      demandMarriageMoreData.value = {}
      basicInfoData.value = {}
      activeKey2.value = '1'
      await resetFields()
      // await resetFields3()
    }
    setModalProps({ minHeight: 480, confirmLoading: false, title })
  })

  // 择偶标准表单配置
  const [registerForm3, { getFieldsValue: getFieldsValue3, setFieldsValue: setFieldsValue3, resetFields: resetFields3 }] =
    useForm({
      labelWidth: 100,
      schemas: demandMarriageSchema,
      baseColProps: { span: 22 },
      showActionButtonGroup: false,
    })

  function close(){
    closeModal()
  }

  function openChange(status) {
    if (status) {
      open.value = true;
    } else {
      open.value = false;
    }
  }

  function disabledDate (current: any) {
    const date: Dayjs = dayjs().subtract(18, 'year')
    return current && current > date.endOf('year')
  }

  function panelChange(value) {
   // 获取到的时间赋值给widgetVal
    setFieldsValue({ birthYear: String(value.year()) });
    open.value = false;
  }

  function uploadAvatarAfter(value) {
    //修改表单的值
    setFieldsValue({ profilePhoto: value });
  }

  async function onInfoChange(){
    if(activeKey2.value == '2' && details.value.datingClueDemand){
      await nextTick()
      const { domicilePlaceProvinceCode, domicilePlaceCityCode } = details.value.datingClueDemand || {}
      const domicilePlace = domicilePlaceCityCode && domicilePlaceProvinceCode ? [domicilePlaceProvinceCode, domicilePlaceCityCode] : []
      const { provinceCode, cityCode, districtCode } = details.value.datingClueDemand || {}
      const address = provinceCode && cityCode && districtCode ? [provinceCode, cityCode, districtCode] : []
      await setFieldsValue3({ ...details.value.datingClueDemand, domicilePlace, address })
    }
  }

  function onUploadRemove({file, index}){
    uploadList.value.splice(index, 1)
  }

  const { createMessage } = useMessage()
  const emits = defineEmits(['success'])
  async function handleOk() {
    try {
      if(ifUpdate.value){
        await importClueRecord({keyList: tableListRef.value[0].header, dataList: tableListRef.value[0].dataSource})
        createMessage.success(`导入成功！`)
        emits('success')
        return
      }
      await validate()
      const values: any = getFieldsValue()
      // console.log({...values, ...basicInfoData.value})
      const { clueTime } = values
      setModalProps({ confirmLoading: true })
      values.clueTime = formatToDate(clueTime)
      const { domicilePlace, address } = values || {}

      const demandInfo: any = getFieldsValue3()
      if(demandInfo){
        const address1 = demandInfo.address
        demandInfo.cityCode =  address1?.[1]
        demandInfo.provinceCode =  address1?.[0]
        demandInfo.districtCode =  address1?.[2]
        const domicilePlace1 = demandInfo.domicilePlace
        demandInfo.domicilePlaceCityCode =  domicilePlace1?.[1]
        demandInfo.domicilePlaceProvinceCode =  domicilePlace1?.[0]
      }
      
      const datingClueDemand = { ...demandInfo, ...demandMarriageMoreData.value }

      var param = {
        ...values, 
        // channelType: 1,
        datingClueDemand,
        cityCode: address?.[1],
        cityName: basicInfoData.value.cityName,
        provinceCode: address?.[0],
        provinceName: basicInfoData.value.provinceName,
        districtCode: address?.[2],
        districtName: basicInfoData.value.districtName,
        domicilePlaceCityCode: domicilePlace?.[1],
        domicilePlaceCityName: basicInfoData.value.domicilePlaceCityName,
        domicilePlaceProvinceName: basicInfoData.value.domicilePlaceProvinceName,
        domicilePlaceProvinceCode: domicilePlace?.[0]
      }
      const datingClueImageList = uploadList.value.map((item: any) => {
        if(item.response && item.response.url){
          return item.response.url
        }
        return item.url
      })
      if(datingClueImageList && datingClueImageList.length){
        param.datingClueImageList = datingClueImageList
      }
      if(details.value && details.value.id){
        param.id = details.value.id
        await editClueRecord(param)
        createMessage.success(`编辑成功！`)
      } else {
        await createClueRecord(param)
        createMessage.success(`新增成功！`)
      }
      emits('success')
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }

  const tableListRef = ref<{ title: string; columns?: any[]; dataSource?: any[]; header:any[];}[]>([]);

  function loadDataSuccess(excelDataList: ExcelData[]) {
    tableListRef.value = [];
    // console.log(excelDataList);
    for (const excelData of excelDataList) {
      const { header, results, meta: { sheetName }, } = excelData;
      const columns: BasicColumn[] = [];
      for (const title of header) {
        columns.push({ title, dataIndex: title });
      }
      tableListRef.value.push({ title: sheetName, dataSource: results, columns, header });
    }
  }

  function exportExcel() {
    downloadByUrl({url: `https://dating-agency-prod.oss-cn-shenzhen.aliyuncs.com/template/线索导入模板.xlsx`});
  }
</script>

<style scoped lang="less">
::v-deep .ant-input-number {
    min-width: 60px;
    width: 100% !important;
    max-width: 100%;
}
</style>
