<!--
 * @Author: wanglj wanglijie@dashoo.cn
 * @Date: 2025-03-24 09:17:15
 * @LastEditors: wanglj wanglijie@dashoo.cn
 * @LastEditTime: 2025-03-26 16:39:21
 * @FilePath: \labsop_h5\src\view\instr\detail.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="container">
    <van-form ref="formRef" required="auto">
      <van-cell-group>
        <van-field label="预约仪器" v-model="state.form.instName" readonly :rules="[{ required: true }]" />
      </van-cell-group>
      <h4>预约时间</h4>
      <van-cell-group class="mt10">
        <van-field
          v-model="state.form.startTime"
          is-link
          readonly
          label="开始时间"
          placeholder="开始时间"
          @click="onRouterPush('/instr-calendar', { id: state.form.instId })"
          :rules="[{ required: true, message: '开始时间不能为空' }]"
        />
        <van-field
          v-model="state.form.endTime"
          is-link
          readonly
          label="结束时间"
          placeholder="结束时间"
          @click="onRouterPush('/instr-calendar', { id: state.form.instId })"
          :rules="[{ required: true, message: '结束时间不能为空' }]"
        />
      </van-cell-group>
      <h4>申请明细</h4>
      <template v-if="state.appointId == 0">
        <van-cell-group class="mt10" v-if="state.isActiveService">
          <!-- <van-field name="radio" label="课题/服务" :rules="[{ required: true }]">
            <template #input>
              <van-radio-group v-model="state.form.projectType" direction="horizontal" @change="changeProjectType">
                <van-radio style="margin-right: 20px" name="project">课题</van-radio>
                <van-radio name="service">服务</van-radio>
              </van-radio-group>
            </template>
          </van-field> -->
          <van-field
            v-if="state.form.projectType == 'project'"
            label="课题组"
            placeholder="课题组"
            @click="state.showProject = true"
            v-model="state.form.projectName"
            :rules="[{ required: true, message: '课题不能为空' }]"
          >
          </van-field>
          <van-field
            v-if="state.form.projectType == 'service'"
            label="服务"
            placeholder="服务"
            @click="state.shwoService = true"
            v-model="state.form.serviceName"
            :rules="[{ required: true, message: '服务不能为空' }]"
          >
          </van-field>
          <!-- <van-field
            v-if="state.form.projectType == 'project'"
            label="经费卡"
            placeholder="经费卡"
            is-link
            readonly
            @click="state.showExpenseCard = true"
            v-model="state.form.expenseCardName"
          ></van-field> -->
          <van-field
            label="预约人"
            placeholder="预约人"
            is-link
            readonly
            @click="openSelectUser"
            v-model="state.form.nickName"
            :rules="[{ required: true, message: '预约人不能为空' }]"
          ></van-field>
          <van-field
            label="联系电话"
            placeholder="联系电话"
            v-model="state.form.userContact"
            :rules="[{ required: true, message: '联系电话不能为空' }]"
          ></van-field>
          <van-field label="备注" placeholder="备注" v-model="state.form.remark" rows="2" autosize type="textarea" maxlength="300" show-word-limit></van-field>
        </van-cell-group>
      </template>
      <CustomForm ref="customFormRef" :formData="state.form.createForm"></CustomForm>
    </van-form>
  </div>
  <van-action-bar>
    <van-action-bar-button class="w100" type="primary" text="提交" @click="onClickButton" />
  </van-action-bar>
  <!-- 选择服务 -->
  <van-popup v-model:show="state.shwoService" position="bottom">
    <van-picker :columns="serviceList" :columns-field-names="{ text: 'name', value: 'id' }" @confirm="pickService" @cancel="state.shwoService = false" />
  </van-popup>
  <!-- 选择课题 -->
  <van-popup v-model:show="state.showProject" position="bottom">
    <van-picker
      :columns="projectList"
      :columns-field-names="{ text: 'projectName', value: 'projectId' }"
      @confirm="pickProject"
      @cancel="state.showProject = false"
    />
  </van-popup>
  <!-- 选择经费卡 -->
  <van-popup v-model:show="state.showExpenseCard" position="bottom">
    <van-picker
      :columns="fundsList"
      :columns-field-names="{ text: 'finAccount', value: 'id' }"
      @confirm="pickExpenseCard"
      @cancel="state.showExpenseCard = false"
    />
  </van-popup>
  <!-- 选择预约人 -->
  <van-popup v-model:show="state.showAppointUser" position="bottom">
    <van-picker
      :columns="userList"
      :columns-field-names="{ text: 'nickName', value: 'id' }"
      @confirm="pickAppointUser"
      @cancel="state.showAppointUser = false"
    />
  </van-popup>
  <AppointDialog ref="appointDialogRef" />
</template>

<script lang="ts" setup>
  import to from 'await-to-js'
  import { useRoute, useRouter } from 'vue-router'
  import { useInstrApi } from '/@/api/instr'
  import { useInstDocApi } from '/@/api/instr/document'
  import { defineAsyncComponent, onMounted, reactive, ref } from 'vue'
  import { formatDate } from '/@/utils/formatTime'
  import { showNotify } from 'vant'
  import download from 'downloadjs'
  import { useNoticeApi } from '/@/api/instr/notice'
  import { useProApi } from '/@/api/project'
  import technicalApi from '/@/api/technical/index'
  import { Local } from '/@/utils/storage'
  import { useUserApi } from '/@/api/system/user'
  import { useUserInfo } from '/@/stores/userInfo'
  import { storeToRefs } from 'pinia'
  import instAppoint from '/@/api/instr/instAppoint'
  import { useConfigApi } from '/@/api/system/config'
  const CustomForm = defineAsyncComponent(() => import('/@/components/CustomForm.vue'))
  const storesUseUserInfo = useUserInfo()
  const { userInfos } = storeToRefs(storesUseUserInfo)
  const route = useRoute()
  const router = useRouter()
  const projApi = useProApi()
  const instApi = useInstrApi()
  const userApi = useUserApi()
  const configApi = useConfigApi()
  const serviceList = ref([])
  const projectList = ref([])
  const fundsList = ref([])
  const userList = ref([])
  const appointDialogRef = ref()
  const formRef = ref()
  const customFormRef = ref()
  const state = reactive({
    loading: false,
    appointId: 0,
    isActiveService: false,
    showProject: false,
    shwoService: false,
    showExpenseCard: false,
    showAppointUser: false,
    isInstrHead: false,
    instDetail: {} as any,
    form: {
      instId: 0,
      instName: '',
      startTime: '',
      endTime: null,
      projectName: null,
      projectId: null,
      serviceId: null,
      serviceName: null,
      expenseCardId: 0,
      expenseCardName: '',
      userContact: '',
      userId: 0,
      nickName: '',
      projectType: '',
      assistEnable: false,
      createForm: [],
      remark: ''
    }
  })

  // 选择课题还是服务
  const changeProjectType = () => {
    state.form.serviceId = 0
    state.form.serviceName = ''
    state.form.projectId = 0
    state.form.projectName = ''
    state.form.expenseCardId = 0
    state.form.expenseCardName = ''
    fundsList.value = []
  }
  const pickProject = ({ selectedOptions }) => {
    state.form.projectId = selectedOptions[0].projectId
    state.form.projectName = selectedOptions[0].projectName
    state.showProject = false
    getFundsData()
  }
  // 选择服务
  const pickService = ({ selectedOptions }) => {
    state.form.serviceId = selectedOptions[0].id
    state.form.serviceName = selectedOptions[0].name
    state.shwoService = false
  }
  // 经费卡选择
  const pickExpenseCard = ({ selectedOptions }) => {
    state.form.expenseCardId = selectedOptions[0].id
    state.form.expenseCardName = selectedOptions[0].finAccount
    state.showExpenseCard = false
  }
  const getFundsData = async () => {
    const [err, res]: ToResponse = await to(projApi.getFinanceAccountList({ projId: state.form.projectId }))
    if (err) return
    fundsList.value = res?.data.list ? [res?.data.list] : []
    // if (fundsList.value && fundsList.value.length > 0 && fundsList.value[0].length > 0) {
    //   state.form.expenseCardId = fundsList.value[0][0].id
    //   state.form.expenseCardName = fundsList.value[0][0].finAccount
    // }
  }
  // 预约人选择
  const pickAppointUser = ({ selectedOptions }) => {
    state.form.nickName = selectedOptions[0].nickName
    state.form.userId = selectedOptions[0].id
    state.form.userContact = selectedOptions[0].phone
    state.showAppointUser = false
    state.form.serviceId = 0
    state.form.serviceName = ''
    state.form.projectId = 0
    state.form.projectName = ''
    state.form.expenseCardId = 0
    state.form.expenseCardName = ''
    fundsList.value = []
    getMyProjectInfo(state.form.userId)
  }
  // 选择预约人
  const openSelectUser = () => {
    if (!state.isInstrHead) return
    state.showAppointUser = true
  }
  const init = async () => {
    //延长预约会传一个预约id 有预约id 获取预约详情
    const [err, res]: ToResponse = await to(configApi.getEntityMapByKey({ configKey: 'instr_is_activate_service' }))
    if (err) return
    state.isActiveService = res.data?.configValue == '10' ? true : false
    state.form.projectType = 'project'
    state.form.userId = userInfos.value.id || 0
    state.form.nickName = userInfos.value.nickName || ''
    state.form.userContact = userInfos.value.phone || ''
    getMyProjectInfo()
    getUserService()
    getUserList()
    getInstrDetails()
    getAppointConfig()
  }
  const getInstrDetails = async () => {
    const [err, res]: ToResponse = await to(instApi.getDetail({ id: state.form.instId }))
    if (err) return
    if (res?.code === 200) {
      state.instDetail = res.data
      state.form.instName = state.instDetail.instName
      const userInfo = storesUseUserInfo.userInfos
      state.isInstrHead = userInfo.id ? res.data.instHeadId.split(',').includes('' + userInfo?.id) : false
    }
  }
  // 获取用户下的服务
  const getUserService = async () => {
    const [err, res]: ToResponse = await to(technicalApi.getList({ noPage: true }))
    if (err) return
    serviceList.value = [res?.data.list]
    if (state.form.projectType == 'service') {
      state.form.serviceId = res?.data.list[0].id || 0
      state.form.serviceName = res?.data.list[0].name || ''
    }
  }
  // 获取用户相关的课题组
  const getMyProjectInfo = async (id?: number) => {
    let params = {}
    if (id) {
      params = { id }
    } else {
      params = {}
    }
    const [err, res]: ToResponse = await to(projApi.getMySelfProjectGroup(params))
    if (err) return
    // state.form.projectName = res?.data.pgName || ''
    // state.form.projectId = res?.data.id || null
    projectList.value = [{ projectName: res?.data.pgName || '', projectId: res?.data.id || null }]
    if (state.form.projectType == 'project') {
      state.form.projectId = res?.data.id || null
      state.form.projectName = res?.data.pgName || ''
      getFundsData()
    }
  }
  const getUserList = async () => {
    const [err, res]: ToResponse = await to(userApi.getUserList({ noPage: true }))
    if (err) return
    userList.value = [res?.data.list]
  }
  // 预约配置信息
  const getAppointConfig = async () => {
    const params = {
      instId: state.form.instId,
      code: 'InstCfgAppoint'
    }
    const [err, res]: ToResponse = await to(instApi.getSettingDetail({ ...params }))
    if (err) return
    state.form.createForm = res?.data?.config.createForm ? JSON.parse(res.data.config.createForm) : []
  }
  const onRouterPush = (val: string, params?: any) => {
    router.push({
      path: val,
      query: { ...params }
    })
  }
  const onClickButton = async () => {
    state.loading = true
    const [errValid] = await to(formRef.value.validate())
    const customForm = customFormRef.value.getFormData()
    if (errValid || (state.form.createForm.length && !customForm)) {
      state.loading = false
      return
    }
    const params = JSON.parse(JSON.stringify(state.form))
    params.userName = params.nickName
    params.sampleForm = JSON.stringify(customForm)
    delete params.createForm
    const [err]: ToResponse = await to(instAppoint.add(params))
    if (err) {
      state.loading = false
      return
    }
    showNotify({
      type: 'success',
      message: '预约成功'
    })
    router.push({
      path: '/instr-detail',
      query: {
        id: params.instId
      }
    })
  }
  onMounted(() => {
    const id = route.query.id ? +route.query.id : 0
    const startTime = route.query.startTime ? formatDate(new Date(+route.query.startTime), 'YYYY-mm-dd HH:MM') : ''
    const endTime = route.query.endTime ? formatDate(new Date(+route.query.endTime), 'YYYY-mm-dd HH:MM') : ''
    state.form.instId = id
    state.form.startTime = startTime
    state.form.endTime = endTime
    init()
  })
</script>

<style lang="scss" scoped>
  .container {
    height: calc(100% - 70px);
    padding: 10px;
    background-color: #f9f9f9;
    overflow-y: auto;
    h4 {
      height: 18px;
      line-height: 18px;
      display: flex;
      margin: 10px 0;
      span {
        font-weight: normal;
        margin-left: auto;
      }
      &::before {
        display: inline-block;
        content: '';
        width: 3px;
        height: 18px;
        background-color: #1c9bfd;
        margin-right: 4px;
        vertical-align: middle;
      }
    }
  }
</style>
