<template>
  <view class="task-box">
    <uv-form labelPosition="left" :model="sendParams">
      <view class="field-box" v-for="(item, index) in configList" :key="item.id">
        <!-- 下拉选择 -->
        <template v-if="isSelectCom(item.taskFiledType)">
          <selectCom
            v-model:selectValue="sendParams[item.taskFiledKey + 'label']"
            :disabled="item.disabled"
            :key="item.id"
            :item="item"
            :index="index"
            :sendParams="sendParams"
            :dictList="dictList"
            v-model:selectDisabled="selectDisabled"
            @isMultiplePickerSearch="isMultiplePickerSearch"
            @confirmFn="confirmFn"
            @updatePackageListFn="updatePackageListFn"
          />
        </template>
        <!-- 树形多选 -->
        <template v-if="item.taskFiledType == 'tree'">
          <treeSelect
            v-model:selectValue="sendParams[item.taskFiledKey + 'label']"
            :selectTreeValue="sendParams[item.taskFiledKey]"
            @treeConfirmFn="treeConfirmFn"
            :item="item"
            :index="index"
            :key="item.id"
            :sendParams="sendParams"
            :dictList="dictList"
          />
        </template>

        <!-- 文字输入 -->
        <template v-if="item.taskFiledType == 'text'">
          <inputCom
            v-model:inputValue="sendParams[item.taskFiledKey]"
            :disabled="item.disabled"
            :item="item"
            :index="index"
          />
        </template>
        <!-- 时间 -->
        <template v-if="item.taskFiledType == 'datetime'">
          <dateTimeCom
            v-model:dateTimeValue="sendParams[item.taskFiledKey]"
            :disabled="item.disabled"
            :item="item"
            :index="index"
          />
        </template>
        <!-- 位置选择 -->
        <template v-if="item.taskFiledType === 'map'">
          <mapCom v-model:mapValue="sendParams[item.taskFiledKey]" :item="item" :index="index" />
        </template>
        <!-- 城市选择 -->
        <template v-if="item.taskFiledType === 'area'">
          <areaCom v-model:areaValue="sendParams[item.taskFiledKey]" :item="item" :index="index" />
        </template>
        <!--联想类型 单选 -->
        <template v-if="item.taskFiledType === 'inputautoselect'">
          <autoSelectCom
            v-model:autoSelecValue="sendParams[item.taskFiledKey + 'label']"
            :sendParams="sendParams"
            :item="item"
            :index="index"
          />
        </template>
        <!-- 数字 金额-->
        <template v-if="item.taskFiledType == 'number' || item.taskFiledType == 'money'">
          <numberCom
            :disabled="item.disabled"
            v-model:numberValue="sendParams[item.taskFiledKey]"
            :item="item"
            :index="index"
          />
        </template>
        <!-- 长文本 -->
        <template v-if="item.taskFiledType == 'longtext'">
          <view class="line-box" />
          <textareaCom
            v-model:textareaValue="sendParams[item.taskFiledKey]"
            :item="item"
            :index="index"
          />
        </template>
        <!-- 日期范围选择 -->
        <template v-if="item.taskFiledType == 'datatimerange'">
          <dateRangeCom
            v-model:dateRangeValue="sendParams[item.taskFiledKey]"
            :item="item"
            :index="index"
          />
        </template>
        <!-- 签名 -->
        <template v-if="item.taskFiledType == 'sign'">
          <view class="line-box" />
          <signCom ref="signComRef" :item="item" :sendParams="sendParams" />
        </template>
        <!-- 图片上传 -->
        <template v-if="item.taskFiledType == 'img'">
          <view class="line-box" />
          <view class="line-box" />
          <imgCom v-model:imgValue="sendParams[item.taskFiledKey]" :item="item" :index="index" />
        </template>
      </view>
    </uv-form>
    <view class="confirm-btn">
      <uv-button class="operate-btn" @click="saveBtn" :customStyle="saveBtnStyle">保存</uv-button>
      <uv-button class="operate-btn" @click="submitBtnFn" :customStyle="submitBtnStyle"
        >提交</uv-button
      >
    </view>
    <!-- 带搜索得多选 -->
    <isMultiplePickerSearchCom
      ref="multiplePickerSearchRef"
      :currValue="currValue"
      @updateMultiplePicker="updateMultiplePicker"
      :dictData="multiplePickerDict"
    />
  </view>
</template>

<script setup lang="ts">
import { onLoad, onShow } from '@dcloudio/uni-app'
import dayjs from 'dayjs'
import { ref, computed, getCurrentInstance, unref } from 'vue'
import {
  getTaskContentConfigByTaskTypeIdApi,
  saveTaskInfoApi,
  getSaveTaskInfoApi,
  saveTaskContentApi
} from '@/service/modules/getTask'
import selectCom from './components/selectCom.vue'
import inputCom from './components/inputCom.vue'
import dateTimeCom from './components/dateTimeCom.vue'
import mapCom from './components/mapCom.vue'
import areaCom from './components/areaCom.vue'
import autoSelectCom from './components/autoSelectCom.vue'
import numberCom from './components/numberCom.vue'
import textareaCom from './components/textareaCom.vue'
import dateRangeCom from './components/dateRangeCom.vue'
import signCom from './components/signCom.vue'
import imgCom from './components/imgCom.vue'
import treeSelect from './components/treeSelect.vue'
import isMultiplePickerSearchCom from './components/isMultiplePickerSearchCom.vue'
import { useTask } from '@/store/task'
import { debounce } from '@/utils/index'

const update = getCurrentInstance()

const taskStore = useTask()
// 任务类型id
const taskTypeId = ref('')

onLoad(async (e) => {
  // 设置标题
  uni.setNavigationBarTitle({
    title: e?.title
  })
  // 保存当前任务类型
  taskTypeId.value = e?.value
  // 获取任务表单信息
  await getTaskContentConfigByTaskTypeId()
  // 获取保存的草稿内容
  await getSaveTaskInfo()
})

const saveBtnStyle = {
  color: 'black',
  width: '350rpx',
  border: '2rpx solid #000'
}
const submitBtnStyle = {
  background: '#6eb657',
  color: '#fff',
  width: '350rpx  '
}

const signComRef = ref()

onShow(() => {
  // taskStore.location有值 是从定位页面返回
  if (taskStore.location) {
    sendParams.value = {
      ...sendParams.value,
      [taskStore.location.sendParamsKey]: taskStore.location.value
    }
    // 清空askStore.location
    taskStore.setLocationSelect(null)
  }
  // 从选择页面
  if (taskStore.autoSelect) {
    sendParams.value = {
      ...sendParams.value,
      [taskStore.autoSelect.sendParamsKey + 'label']: taskStore.autoSelect.label
    }
    sendParams.value = {
      ...sendParams.value,
      [taskStore.autoSelect.sendParamsKey]: taskStore.autoSelect.value,
      temp28: taskStore.autoSelect.activeId + ''
    }
    // 清空askStore.autoSelect
    taskStore.setAutoSelect(null)
  }
  // 签名页面返回
  if (taskStore.sign) {
    sendParams.value = {
      ...sendParams.value,
      [taskStore.sign.sendParamsKey]: taskStore.sign.url
    }
    uni.$emit('imgShow', taskStore.sign.url)
    taskStore.setSign(null)
  }
  // 从药店选择页面返回
  if (taskStore.pharmacySelect) {
    sendParams.value = {
      ...sendParams.value,
      [taskStore.pharmacySelect.sendParamsKey]: taskStore.pharmacySelect.pharmacyName,
      [taskStore.pharmacySelect.sendParamsKey + 'label']: taskStore.pharmacySelect.pharmacyName,
      [taskStore.pharmacySelect.sendParamsKey + 'Id']: taskStore.pharmacySelect.id,
      temp4: taskStore.pharmacySelect.address,
      temp7: taskStore.pharmacySelect.area,
      temp7label: taskStore.pharmacySelect.area
    }
    taskStore.setpPharmacySelect(null)
  }
  // 单选返回并且是新增
  if (taskStore.singleSelecttByAdd) {
    sendParams.value = {
      ...sendParams.value,
      [taskStore.singleSelecttByAdd.sendParamsKey]: taskStore.singleSelecttByAdd.name,
      [taskStore.singleSelecttByAdd.sendParamsKey + 'label']: taskStore.singleSelecttByAdd.name
    }
    taskStore.setSingleSelectByAdd(null)
  }
  // 医院或商业公司页面返回
  if (taskStore.singleSelect) {
    // 医院
    if (taskStore.singleSelect.taskTypeId === '15') {
      hospitalInfo(taskStore.singleSelect.data)
      // 药店
    } else if (taskStore.singleSelect.taskTypeId === '16') {
      companiesInfo(taskStore.singleSelect.data)
      // 其他单选
    } else {
      const data = taskStore.singleSelect.data
      sendParams.value = {
        ...sendParams.value,
        [taskStore.singleSelect.sendParamsKey]: data.yymc || data.gsmc,
        [taskStore.singleSelect.sendParamsKey + 'label']: data.yymc || data.gsmc
      }
    }
    taskStore.setSingleSelect(null)
  }

  // 拜访类任务
  if (taskStore.signAddressInfo) {
    const startTime = dayjs(taskStore.signAddressInfo.signTime)
    const endTime = dayjs(taskStore.signAddressInfo.checkOutTime)

    // 计算两个时间之间的差异，以分钟为单位
    const diffInMinutes = endTime.diff(startTime, 'minute')
    sendParams.value = {
      ...sendParams.value,
      // 签到时长
      temp15: `${diffInMinutes} 分钟`,
      // 签到企业类型
      temp8: taskStore.signAddressInfo.signEntType,
      // 地点id
      temp9: taskStore.signAddressInfo.locationId,
      // 地点信息
      temp10: taskStore.signAddressInfo.address,
      // 纬度
      temp11: taskStore.signAddressInfo.latitude,
      // 经度
      temp12: taskStore.signAddressInfo.longitude,
      // 地点id
      temp24: taskStore.signAddressInfo.locationId,
      // 地点信息
      temp24label: taskStore.signAddressInfo.address,
      // 签到时间
      temp25: taskStore.signAddressInfo.signTime,
      temp7: taskStore.signAddressInfo.checkOutTime
    }
    // temp24
    taskStore.setSignAddressInfo(null)
  }
  update!.proxy!.$forceUpdate()
})

// 提交表单
interface SendParams {
  [key: string]: string | undefined
}
const sendParams = ref<SendParams>({})

// 当配置表单为数组
const configListArr = ref()
// 当前表单
const configList = ref()
// 当前表单字典
const dictList = ref<any>()
const getTaskContentConfigByTaskTypeId = async () => {
  const res = await getTaskContentConfigByTaskTypeIdApi(taskTypeId.value)
  if (res.code !== 0) {
    return uni.showToast({
      title: res.msg,
      icon: 'none'
    })
  }
  // 单个表单
  if (res.data.config) {
    configList.value = res.data.config
    dictList.value = res.data.dict
  } else {
    // 多个表单内容
    configListArr.value = res.data
    // 选出当前任务类型
    configList.value = configListArr.value[taskTypeId.value].config
    dictList.value = configListArr.value[taskTypeId.value].dict
  }
  // 循环表单 当发现类型为 datetime  默认设置为当前时间
  configList.value.forEach((item: any) => {
    item.disabled = false
    // 拜访任务类型禁用

    item.taskTypeId = item.taskTypeId?.trim()

    if (item.taskFiledType === 'datetime' && item.taskTypeId != '12') {
      if (item.taskFiledKey) {
        sendParams.value = {
          ...sendParams.value,
          [item.taskFiledKey]: dayjs(new Date()).format('YYYY-MM-DD HH:mm')
        }
      }

      // 日期禁止选择
      const arr = ['53']
      if (arr.includes(item.taskTypeId)) {
        item.disabled = true
      }
    }
    const arr = ['51', '52', '53']

    if (arr.includes(item.taskTypeId)) {
      // 24 拜访地点  25 签到时间   temp7 签退时间 temp15 签退时间
      const disabledItem = ['temp24', 'temp25', 'temp7', 'temp15']
      if (disabledItem.includes(item.taskFiledKey)) {
        item.disabled = true
      }
    }
    // 一对一专访 下拉选项为一条 禁用下拉选项
    if (
      item.taskTypeId == 19 &&
      item.taskFiledKey === 'temp3' &&
      dictList.value[item.dictGroupName].length === 1
    ) {
      sendParams.value = {
        ...sendParams.value,
        temp3label: dictList.value[item.dictGroupName][0].label,
        temp3: dictList.value[item.dictGroupName][0].value
      }
    }
  })
}

// 展示select
const isSelectCom = computed(() => {
  return (taskFiledType: string) => {
    return taskFiledType === 'domain' || taskFiledType === 'select'
  }
})
const multiplePickerSearchRef = ref()
const multiplePickerDict = ref()
const currValue = ref()
// 带搜索的多选
const isMultiplePickerSearch = () => {
  multiplePickerDict.value = dictList.value.medical_equipment_list
  currValue.value = sendParams.value.temp12
  multiplePickerSearchRef.value.open()
}

// 带筛选的多选
const updateMultiplePicker = (data: any) => {
  const arr = data.join(',')
  sendParams.value = {
    ...sendParams.value,
    temp12: arr,
    temp12label: arr
  }
}

// select选择确认
const confirmFn = (taskFiledKey: string, label: string, value: string) => {
  sendParams.value = {
    ...sendParams.value,
    [taskFiledKey]: value
  }
  sendParams.value = {
    ...sendParams.value,
    [taskFiledKey + 'label']: label
  }
}

// tree 选择
const treeConfirmFn = (taskFiledKey: string, label: string, value: string) => {
  sendParams.value = {
    ...sendParams.value,
    [taskFiledKey]: value
  }
  sendParams.value = {
    ...sendParams.value,
    [taskFiledKey + 'label']: label
  }
}
// 暂时禁用
const selectDisabled = ref(false)
// 会议举办1 培训34 更新package_list数据
const updatePackageListFn = (data: any) => {
  sendParams.value.temp32 = ''
  sendParams.value.temp32label = ''
  dictList.value.package_list = data
}

//!获取保存的草稿内容
const getSaveTaskInfo = async () => {
  const res = await getSaveTaskInfoApi(taskTypeId.value)
  if (res.data && Object.keys(res.data).length) {
    let data = res.data
    for (let key in data) {
      if (data[key]) {
        sendParams.value = {
          ...sendParams.value,
          [key]: data[key]
        }
      }
    }
  }
}

//! 保存
const saveBtn = async () => {
  sendParams.value = {
    ...sendParams.value,
    draftKey: taskTypeId.value,
    temp30: taskTypeId.value
  }
  uni.showLoading()
  try {
    const res = await saveTaskInfoApi(sendParams.value)
    uni.hideLoading()
    if (res.code === 1) {
      return uni.showToast({
        title: res.msg,
        icon: 'none'
      })
    } else if (res.code === 0) {
      uni.showToast({
        title: '保存成功',
        icon: 'none',
        duration: 1000
      })
      setTimeout(() => {
        // 拜访类任务
        const arr = ['51', '52', '53']
        if (arr.includes(taskTypeId.value)) {
          uni.switchTab({
            url: '/pages/index/index'
          })
        } else {
          uni.navigateBack()
        }
      }, 2000)
    }
  } catch (e) {
    uni.hideLoading()
    console.log('error', e)
  }
}

let isSubmitting = false
// 提交函数
const submitBtn = async () => {
  if (isSubmitting) return
  if (!validateForm()) return

  isSubmitting = true // 标记正在提交
  sendParams.value = {
    ...sendParams.value,
    draftKey: taskTypeId.value,
    temp30: taskTypeId.value
  }

  uni.showLoading({
    title: '提交中...',
    mask: true
  })
  try {
    const res = await saveTaskContentApi(sendParams.value)
    if (res.code === 0) {
      handleSuccess(res)
    } else {
      handleError(res.msg)
    }
  } catch (e) {
    console.error('提交出错', e)
    uni.showToast({ title: '提交失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

// 成功处理
const handleSuccess = (res: any) => {
  uni.hideLoading()
  let title = `提交成功,获得${res.data.score}积分`
  sendParams.value = {}
  if (res.data.type == '2') {
    title = `完成任务数+1`
  }
  uni.showToast({
    title: title,
    icon: 'none',
    duration: 500
  })
  setTimeout(() => {
    const arr = ['51', '52', '53']
    if (arr.includes(taskTypeId.value)) {
      uni.switchTab({
        url: '/pages/index/index'
      })
    } else {
      uni.navigateBack()
    }
  }, 700)
}

// 错误处理
const handleError = (msg: string) => {
  uni.hideLoading()
  uni.showModal({
    title: '提示',
    showCancel: false,
    content: msg,
    success: function (res) {
      if (res.confirm) {
        isSubmitting = false // 恢复提交状态
        console.log('用户点击确定')
      }
    }
  })
}

const submitBtnFn = debounce(submitBtn, 1500)
// 校验表单
const validateForm = () => {
  let sendParamsValue = unref(sendParams)
  for (let item of configList.value) {
    // 当内容为必填 但是为空 表单未完善
    if (item.isMustfill === '1' && !sendParamsValue[item.taskFiledKey]) {
      uni.showToast({
        title: `请完善${item.taskFiledValue}`,
        icon: 'none'
      })
      return
    }
    // 是必填并且是图片的时候
    if (item.isMustfill === '1' && item.taskFiledType == 'img') {
      const imgArr = sendParamsValue[item.taskFiledKey]?.split(',')
      if (imgArr && item?.taskFiledMinsize > imgArr?.length) {
        uni.showToast({
          title: `${item.taskFiledValue}至少上传${item.taskFiledMinsize}图片`,
          icon: 'none'
        })
        return
      }
    }

    if (item.taskFiledValue === '会议时长' && item.taskFiledType == 'number') {
      if (
        item?.taskFiledMinsize > 0 &&
        sendParamsValue[item.taskFiledKey]! < item?.taskFiledMinsize
      ) {
        uni.showToast({
          title: `会议时长不能少于${item?.taskFiledMinsize}分钟`,
          icon: 'none'
        })
        return
      }
    }

    if (
      item.isMustfill === '1' &&
      (item.taskFiledType == 'text' || item.taskFiledType == 'longtext')
    ) {
      const length = sendParamsValue[item.taskFiledKey]?.length || 0
      if (item?.taskFiledMinsize && length < item?.taskFiledMinsize) {
        uni.showToast({
          title: `${item.taskFiledValue}不能少于${item?.taskFiledMinsize}个字符`,
          icon: 'none'
        })
        return
      }
    }
  }
  return true
}
// 只针对医院信息回显
const hospitalInfo = (data: any) => {
  let levellabel = ''
  if (dictList.value?.hospital_level.length) {
    let curr = dictList.value?.hospital_level.find((item: any) => item.value === data.yygm)
    if (curr) {
      levellabel = curr.label
    }
  }
  let typelabel = ''
  if (dictList.value?.hospital_xz.length) {
    let curr = dictList.value?.hospital_xz.find((item: any) => item.value === data.yyxz)
    if (curr) {
      typelabel = curr.label
    }
  }
  let sickbedCount = ''
  if (dictList.value?.hospital_cw.length) {
    let curr = dictList.value?.hospital_cw.find((item: any) => item.value === data.ybczs)
    if (curr) {
      sickbedCount = curr.label
    }
  }
  let temp4 = ''
  if (data?.province && data?.city && data?.area) {
    temp4 = `${data?.province}-${data?.city}-${data?.area}`
  }
  const info = {
    temp3: data.yymc || data.gsmc,
    temp3label: data.yymc || data.gsmc,
    temp4: temp4,
    temp16: data.address,
    temp5: data.yygm,
    temp5label: levellabel,
    temp6: data.yyxz,
    temp6label: typelabel,
    temp8: data.website,
    temp22: data.ybczs,
    temp22label: sickbedCount
  }

  sendParams.value = {
    ...sendParams.value,
    ...info
  }
}

const companiesInfo = (data: any) => {
  let levellabel = ''
  if (dictList.value?.bus_gsgm.length) {
    let curr = dictList.value?.bus_gsgm.find((item: any) => item.value === data.gsgm)
    if (curr) {
      levellabel = curr.label
    }
  }
  const info = {
    temp3: data.yymc || data.gsmc,
    temp3label: data.yymc || data.gsmc,
    temp4: `${data?.province}-${data?.city}-${data?.area}`,
    temp5: data.gsgm,
    temp5label: levellabel,
    temp6: data.shyshxydm,
    temp7: data.gszcd,
    temp7label: data.gszcd,
    temp8: data.zczb,
    temp9: data.zczb,
    temp10: data.frdb,
    temp20: data.gsjj,
    temp21: data.jyys,
    temp22: data.medicineTraceability,
    temp22label: data.medicineTraceabilityName,
    temp25: data.medicineTraceabilityOther
  }

  sendParams.value = {
    ...sendParams.value,
    ...info
  }
}
</script>

<style lang="scss" scoped>
.task-box {
  padding-bottom: 160rpx;
  background: #f2f2f2;
  min-height: 100vh;

  :deep(.uv-form-item) {
    background-color: #fff;
    padding: 0 20rpx 0 30rpx;
  }
  .line-box {
    width: 100%;
    height: 20rpx;
    background: #f4f4f4;
  }
  .confirm-btn {
    box-shadow: 0px 0px 8rpx 0px rgba(193, 193, 193, 0.5);
    padding: 28rpx 16rpx;
    background: #ffffff;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 9;
    display: flex;
    justify-content: space-between;
    .operate-btn {
      width: calc(50% - 8rpx);
    }
  }
}
</style>
