<script lang="ts" setup>
import { ref } from 'vue'
import { useToast } from 'wot-design-uni'
import {
  addtodoaskslist,
  getPostList,
  queryExecutorList,
  querybaseApilist,
  queryrCCList,
  selectAllSysStation,
} from '@/api/workorder/index'
import { getDictOptions } from '@/utils/dict'
import { uploadUrl } from '@/utils/uploadFile'
const uploadAction = uploadUrl.USER_AVATAR
const DICT_KEYS = {
  TASK_TYPE: 'task_type',
  WF_FORM_TYPE: 'wf_form_type',
  FORMT_TYPE: 'form_type',
}
const toast = useToast()
//  options: [
//   { value: 'photo', label: '新增拍照任务' },
//   { value: 'inspection', label: '新增检查任务' },
//   { value: '3', label: '选择任务模板' },
//   ],

// const radiovalue = ref('1')
const getoptions = ref('')
const UploadList = ref([])
const form = ref()
const getPostListOptions = ref([]) as any //执行岗位
const getStationIdListOptions = ref([]) as any //场站名称
const getUserListOptions = ref([]) as any //执行人名称
const getCCrListOptions = ref([]) as any //抄送人名称
const getTemplateListOptions = ref([]) as any //任务模板列表
const postListLoading = ref(false) //执行岗位加载状态
const stationIdListLoading = ref(false) //场站名称加载状态
const userListLoading = ref(false) //执行人名称加载状态
const ccListLoading = ref(false) //抄送人名称加载状态
const getTaskTypeOptions = () => getDictOptions(DICT_KEYS.TASK_TYPE) //任务类型

onLoad((options) => {
  getoptions.value = options.type
  model.value.type =
    getoptions.value === '新增油站'
      ? '1'
      : getoptions.value === '新增访客'
        ? '2'
        : ''
})
const model = ref({
  type: '',
  executePosition: '',
  stationId: [],
  executorIds: [],
  // executors: [],
  formType: 'photo',
  templateId: '',
  taskName: '',
  startTime: '',
  endTime: '',
  taskType: '',
  ccReceivers: [],
  // ccReceiversName: [],
  description: '',
  attachments: '',
}) as any

const getPostListfn = async () => {
  if (getPostListOptions.value.length > 0) {
    return
  }
  postListLoading.value = true
  try {
    const { code, rows } = (await getPostList({})) as any
    if (code === 200) {
      getPostListOptions.value =
        getoptions.value === '新增油站'
          ? rows
              .filter((item: any) => item.postId === 3)
              .map((items) => ({ label: items.postName, value: items.postId }))
          : getoptions.value === '新增访客'
            ? rows?.map((items) => ({
                label: items.postName,
                value: items.postId,
              }))
            : []
    } else {
      uni.showToast({
        icon: 'error',
        title: '获取岗位列表失败',
      })
    }
  } catch (error) {
    uni.showToast({
      icon: 'error',
      title: '获取岗位列表失败',
    })
  } finally {
    postListLoading.value = false
  }
}

// 场站名称
const getstationIdListfn = async () => {
  if (getStationIdListOptions.value.length > 0) {
    return
  }
  stationIdListLoading.value = true
  try {
    const { code, data } = (await selectAllSysStation()) as any
    if (code === 200) {
      getStationIdListOptions.value = data.map((item: any) => ({
        label: item.stationName,
        value: item.id,
      }))
    } else {
      uni.showToast({
        icon: 'error',
        title: '获取场站名称列表失败',
      })
    }
  } catch (error) {
    uni.showToast({
      icon: 'error',
      title: '获取场站名称列表失败',
    })
  } finally {
    stationIdListLoading.value = false
  }
}
//执行人
const getUserListfn = async () => {
  if (getUserListOptions.value.length > 0) {
    return
  }
  userListLoading.value = true
  try {
    const { code, data } = (await queryExecutorList({})) as any
    if (code === 200) {
      getUserListOptions.value = data.map((item: any) => ({
        label: `${item.userName}-${item.postName}-${item.stationName}`,
        value: JSON.stringify(item),
        postId: item.postId,
      }))
    } else {
      uni.showToast({
        icon: 'error',
        title: '获取执行人列表失败',
      })
    }
  } catch (error) {
    uni.showToast({
      icon: 'error',
      title: '获取执行人列表失败',
    })
  } finally {
    userListLoading.value = false
  }
}
//抄送人
const getCCListfn = async () => {
  if (getCCrListOptions.value.length > 0) {
    return
  }
  ccListLoading.value = true
  try {
    const { code, rows } = (await queryrCCList()) as any
    if (code === 200) {
      getCCrListOptions.value = rows.map((item: any) => ({
        label: item.userName,
        value: item.userId,
      }))
    } else {
      uni.showToast({
        icon: 'error',
        title: '获取抄送人列表失败',
      })
    }
  } catch (error) {
    uni.showToast({
      icon: 'error',
      title: '获取抄送人列表失败',
    })
  } finally {
    ccListLoading.value = false
  }
}
const querybaseApilistfn = async () => {
  if (getTemplateListOptions.value.length > 0) {
    return
  }
  try {
    const { code, rows } = (await querybaseApilist({
      status: 0,
      pageNum: 1,
      pageSize: 1000,
    })) as any
    if (code === 200) {
      getTemplateListOptions.value = rows.map((item: any) => ({
        ...item,
        label: item.taskName,
        value: item.id,
      }))
    } else {
      toast.error('获取任务模板列表失败')
    }
  } catch (error) {
    toast.error('获取任务模板列表失败')
  }
}
// 处理开始时间确认
const handleStartTimeConfirm = ({ value }) => {
  const date = new Date(value)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  model.value.startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
// 处理结束时间确认
const handleEndTimeConfirm = ({ value }) => {
  const date = new Date(value)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  model.value.endTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
function handleSubmit() {
  form.value
    .validate()
    .then(async ({ valid, errors }) => {
      if (valid) {
        const submitData = {
          ...model.value,
          attachments: UploadList.value
            .map((item) => JSON.parse(item.response).data.fileName)
            .filter(Boolean)
            .join(','),
          executorIds: model.value.executorIds.map((item) => JSON.parse(item)),
          // executors: model.value.executorIds.map((item) =>
          //   String(JSON.parse(item).userId)
          // ),
          ccReceivers: model.value.ccReceivers.join(','),
          // ccReceiversName: model.value.ccReceivers.map((item) =>
          //   String(JSON.parse(item).userId)
          // ),
        }
        if (
          model.value.formType === 'photo' ||
          model.value.formType === 'inspection'
        ) {
          delete submitData.templateId
        } else if (model.value.formType === '3') {
          // delete submitData.taskName
          // submitData.formType = ''
          submitData.taskName =
            getTemplateListOptions.value.find(
              (item) => item.id === Number(model.value.templateId)
            )?.taskName || ''
        }
        if (getoptions.value === '新增油站') {
          //  submitData['executorIds']=model.value.executorIds.map((item) => JSON.parse(item))
          delete submitData.stationId
        } else if (getoptions.value === '新增访客') {
          //  submitData['executorId']=model.value.executorIds.map((item) => JSON.parse(item))
          //  delete submitData.executorIds
          submitData.stationId = model.value.stationId.join(',')
        }
        const res = (await addtodoaskslist(submitData)) as any
        if (res?.code === 200) {
          uni.showToast({
            icon: 'success',
            title: '操作成功',
          })
        }
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
const handleTemplateconfirm = (data) => {
  if (model.value.formType === '3') {
    const findobj = getTemplateListOptions.value.find(
      (item) => item.id === Number(data.value)
    )
    model.value.taskType = findobj?.taskType || ''
    model.value.description = findobj?.description || ''
  }
}
const handleChange = ({ value }) => {
  if (value === 'photo' || value === 'inspection') {
    model.value.taskType = ''
    model.value.description = ''
  } else {
    if (model.value.templateId) {
      const findobj = getTemplateListOptions.value.find(
        (item) => item.id === Number(model.value.templateId)
      )
      model.value.taskType = findobj?.taskType || ''
      model.value.description = findobj?.description || ''
    }
  }
}
const handleUploadSuccess = ({ file, fileList, formData }) => {
  UploadList.value = [...fileList]
}
const handleUploadRemove = ({ file }) => {
  UploadList.value = UploadList.value.filter((item) => item.uid !== file.uid)
}
</script>
<template>
  <view style="padding: 30rpx; box-sizing: border-box">
    <wd-form ref="form" :model="model">
      <wd-cell-group>
        <!-- clearable -->
        <view style="display: flex; flex-direction: column; gap: 20rpx">
          <view>
            <view style="display: flex; align-items: center; gap: 4rpx">
              <text style="color: #fa4350; font-size: 28rpx; font-weight: bold"
                >*</text
              >
              <text style="color: #31373d">执行岗位</text>
            </view>
            <wd-picker
              style="border-bottom: 1rpx solid #e5e5e5"
              label-width="100px"
              prop="executePosition"
              v-model="model.executePosition"
              placeholder="请选择执行岗位"
              :rules="[{ required: true, message: '请选择执行岗位' }]"
              custom-class="custom-vertical-input"
              @open="getPostListfn"
              :columns="getPostListOptions"
              :loading="postListLoading"
            />
          </view>

          <view v-if="getoptions === '新增访客'">
            <view style="display: flex; align-items: center; gap: 4rpx">
              <text style="color: #fa4350; font-size: 28rpx; font-weight: bold"
                >*</text
              >
              <text style="color: #31373d">场站名称</text>
            </view>
            <wd-select-picker
              style="border-bottom: 1rpx solid #e5e5e5"
              type="checkbox"
              label-width="100px"
              prop="stationId"
              v-model="model.stationId"
              placeholder="请选择场站名称"
              :rules="[{ required: true, message: '请选择场站名称' }]"
              custom-class="custom-vertical-input"
              @open="getstationIdListfn"
              :columns="getStationIdListOptions"
              :loading="stationIdListLoading"
            />
          </view>

          <view>
            <view style="display: flex; align-items: center; gap: 4rpx">
              <text style="color: #fa4350; font-size: 28rpx; font-weight: bold"
                >*</text
              >
              <text style="color: #31373d">执行人名称</text>
            </view>
            <wd-select-picker
              style="border-bottom: 1rpx solid #e5e5e5"
              type="checkbox"
              label-width="100px"
              prop="executorIds"
              v-model="model.executorIds"
              placeholder="请选择执行人名称"
              :rules="[{ required: true, message: '请选择执行人名称' }]"
              custom-class="custom-vertical-input"
              @open="getUserListfn"
              :columns="
                getoptions === '新增油站'
                  ? getUserListOptions.filter((item: any) => item.postId === 3)
                  : getUserListOptions
              "
              :loading="userListLoading"
            />
          </view>

          <view
            style="
              display: flex;
              flex-direction: column;
              gap: 20rpx;
              margin-top: 16rpx;
            "
          >
            <view style="display: flex; align-items: center; gap: 10rpx">
              <view
                style="
                  display: flex;
                  align-items: center;
                  gap: 4rpx;
                  width: 5.875rem;
                "
              >
                <text
                  style="color: #fa4350; font-size: 28rpx; font-weight: bold"
                  >*</text
                >
                <text style="color: #31373d">任务名称</text>
              </view>
              <wd-radio-group
                v-model="model.formType"
                inline
                shape="dot"
                @change="handleChange"
              >
                <wd-radio value="photo">新增拍照任务</wd-radio>
                <wd-radio value="inspection" v-if="getoptions === '新增访客'"
                  >新增检查任务</wd-radio
                >
                <wd-radio value="3">选择任务模板</wd-radio>
              </wd-radio-group>
            </view>
            <view>
              <wd-input
                v-if="
                  model.formType === 'photo' || model.formType === 'inspection'
                "
                prop="taskName"
                v-model="model.taskName"
                placeholder="请输入任务名称"
                :rules="[{ required: true, message: '请填写任务名称' }]"
              />
              <wd-picker
                v-else-if="model.formType === '3'"
                style="border-bottom: 1rpx solid #e5e5e5"
                prop="templateId"
                v-model="model.templateId"
                placeholder="请选择任务模板"
                :rules="[{ required: true, message: '请选择任务模板' }]"
                custom-class="custom-vertical-input"
                @open="querybaseApilistfn"
                :columns="getTemplateListOptions"
                @confirm="handleTemplateconfirm"
              />
            </view>
          </view>

          <view>
            <view style="display: flex; align-items: center; gap: 4rpx">
              <text style="color: #fa4350; font-size: 28rpx; font-weight: bold"
                >*</text
              >
              <text style="color: #31373d">开始日期</text>
            </view>
            <wd-calendar
              style="border-bottom: 1rpx solid #e5e5e5"
              label-width="100px"
              type="datetime"
              v-model="model.startTime"
              prop="startTime"
              placeholder="请选择开始日期"
              :rules="[{ required: true, message: '请选择开始日期' }]"
              @confirm="handleStartTimeConfirm"
            />
          </view>

          <view>
            <view style="display: flex; align-items: center; gap: 4rpx">
              <text style="color: #fa4350; font-size: 28rpx; font-weight: bold"
                >*</text
              >
              <text style="color: #31373d">结束日期</text>
            </view>
            <wd-calendar
              style="border-bottom: 1rpx solid #e5e5e5"
              label-width="100px"
              type="datetime"
              v-model="model.endTime"
              prop="endTime"
              placeholder="请选择结束日期"
              :rules="[{ required: true, message: '请选择结束日期' }]"
              @confirm="handleEndTimeConfirm"
            />
          </view>

          <view>
            <view style="display: flex; align-items: center; gap: 4rpx">
              <text style="color: #fa4350; font-size: 28rpx; font-weight: bold"
                >*</text
              >
              <text style="color: #31373d">任务类型</text>
            </view>
            <wd-picker
              style="border-bottom: 1rpx solid #e5e5e5"
              :disabled="model.formType === '3'"
              label-width="100px"
              prop="taskType"
              v-model="model.taskType"
              placeholder="请选择任务类型"
              :rules="[{ required: true, message: '请选择任务类型' }]"
              :columns="getTaskTypeOptions()"
            />
          </view>

          <view>
            <view style="display: flex; align-items: center; gap: 4rpx">
              <text style="color: #fa4350; font-size: 28rpx; font-weight: bold"
                >*</text
              >
              <text style="color: #31373d">抄送人名称</text>
            </view>
            <wd-select-picker
              style="border-bottom: 1rpx solid #e5e5e5"
              type="checkbox"
              label-width="100px"
              prop="ccReceivers"
              v-model="model.ccReceivers"
              placeholder="请选择抄送人"
              :rules="[{ required: true, message: '请选择抄送人' }]"
              custom-class="custom-vertical-input"
              @open="getCCListfn"
              :columns="getCCrListOptions"
              :loading="ccListLoading"
            />
          </view>

          <view>
            <view style="display: flex; align-items: center; gap: 4rpx">
              <!-- <text style="color: #fa4350; font-size: 28rpx; font-weight: bold"
                >*</text
              > -->
              <text style="color: #31373d">任务描述</text>
            </view>
            <wd-textarea
              style="border-bottom: 1rpx solid #e5e5e5; box-sizing: border-box"
              :disabled="model.formType === '3'"
              label-width="100px"
              v-model="model.description"
              placeholder="请填写任务描述"
              :maxlength="500"
              :show-word-limit="true"
            />
          </view>

          <view style="display: flex; gap: 14rpx; align-items: center">
            <view style="display: flex; align-items: center; gap: 4rpx">
              <!-- <text style="color: #fa4350; font-size: 28rpx; font-weight: bold"
                >*</text
              > -->
              <text style="color: #31373d">附件</text>
            </view>
            <wd-upload
              :file-list="UploadList"
              :action="uploadAction"
              image-mode="aspectFill"
              @success="handleUploadSuccess"
              @remove="handleUploadRemove"
            >
              <wd-button plain size="small" style="border-radius: 8rpx"
                >上传附件</wd-button
              >
            </wd-upload>
          </view>
        </view>
      </wd-cell-group>
      <view class="footer" style="margin-top: 100rpx">
        <wd-button
          style="border-radius: 8rpx"
          type="primary"
          size="large"
          @click="handleSubmit"
          block
          >提交</wd-button
        >
      </view>
    </wd-form>
  </view>
</template>
<style lang="scss" scoped></style>
