<script setup>
import dayjs from 'dayjs'
import { getElevatorInfoApi, postWorkDataDistributionApi } from '@/api/elevator'
import { useUpload } from '@/composables/use-upload'
import { tryFormValidate } from '@/helper/async'

const { uploadFile } = useUpload()

const elevatorList = ref([])
const elevatorInfo = ref({})
const getElevatorInfo = async () => {
  const { error, data } = await getElevatorInfoApi(options.value)
  if (error) {
    return
  }
  elevatorInfo.value = data
  elevatorList.value = [
    {
      id: data.id,
      name: data.elevatorName
    }
  ]
}

const showAction = ref(false)
const actionSelect = (e) => {
  console.log('actionSelect', e)
  const { name, value } = e
  model.value.planTypeName = name
  model.value.planType = value
}
const actions = [
  { name: '系统调整优化', value: 11 },
  { name: '维修换件', value: 12 }
]
const hideKeyboard = () => {
  uni.hideKeyboard()
}

const showCalendar = ref(false)
const calendarConfirm = ([time]) => {
  console.log('calendarConfirm', time)
  showCalendar.value = false
  model.value.expectTime = time
}
const calendarClose = () => {
  showCalendar.value = false
  form.value.validateField('expectTime')
}

const form = ref(null)
const model = ref({
  // 1.救援 2.维修 3.维保
  workType: 2,
  planType: '',
  planTypeName: '',
  elevatorNum: '',
  expectTime: dayjs().format('YYYY-MM-DD'),
  publisher: '',
  // 零部件名称
  partName: '',
  // 规格型号
  partModel: '',
  // 数量
  partNum: '',
  // 材料报价
  materialQuote: '',
  // 人工及杂费
  otherExpenses: '',
  // 总预算
  totalBudget: '',
  // 图片
  repairBeforeRecord: '',
  description: ''
})
watchEffect(() => {
  const materialQuote = model.value.materialQuote || 0
  const otherExpenses = model.value.otherExpenses || 0
  model.value.totalBudget = (
    parseFloat(materialQuote) + parseFloat(otherExpenses)
  ).toString()
})
const fileList = ref([])
const afterRead = ({ file }) => {
  const { thumb } = file
  uploadFile([thumb], async ({ url }) => {
    fileList.value.push({ url, thumb })
    model.value.repairBeforeRecord = url
  })
}
const deletePic = (index) => {
  fileList.value.splice(index, 1)
  model.value.repairBeforeRecord = ''
}
const rules = ref({
  planType: {
    type: 'number',
    required: true,
    message: '请选择维修类型',
    trigger: ['change']
  },
  expectTime: {
    type: 'string',
    required: true,
    message: '请选择期望时间',
    trigger: ['change']
  },
  partName: {
    type: 'string',
    required: true,
    message: '请输入零部件名称',
    trigger: ['blur']
  },
  partModel: {
    type: 'string',
    required: true,
    message: '请输入规格型号',
    trigger: ['blur']
  },
  partNum: {
    type: 'string',
    required: true,
    message: '请输入数量',
    trigger: ['blur']
  },
  materialQuote: {
    type: 'string',
    required: true,
    message: '请输入材料报价',
    trigger: ['blur']
  },
  otherExpenses: {
    type: 'string',
    required: true,
    message: '请输入人工及杂费',
    trigger: ['blur']
  },
  // description: {
  //   type:'string',
  //   required: true,
  //   message: '请输入工作描述',
  //   trigger: ['blur']
  // },
  repairBeforeRecord: {
    type: 'string',
    required: true,
    message: '请上传维修前照片',
    trigger: ['change']
  }
})

const submit = async () => {
  const [isOk] = await tryFormValidate(form)
  if (isOk) {
    console.log(model.value)
    const { partName, partModel, partNum } = model.value
    const repairMaterialData = JSON.stringify({
      partName,
      partModel,
      partNum
    })
    const { error } = await postWorkDataDistributionApi({
      ...model.value,
      repairMaterialData,
      elevatorList: elevatorList.value
    })
    if (!error) {
      uni.$u.toast('提交成功')
      uni.navigateBack({
        delta: 2
      })
    } else {
      uni.$u.toast('提交失败，请稍后重试')
    }
  } else {
    uni.$u.toast('请填写完整信息')
  }
}

const options = ref({})
onLoad(async (e) => {
  options.value = e
  getElevatorInfo()

  model.value.elevatorNum = e.elevatorNum

  const { nickName } = uni.getStorageSync('userInfo')
  model.value.publisher = nickName
})
</script>

<template>
  <!-- 基本信息 -->
  <view my-20 px-30>
    <view text-40 text-bold mt-20>{{ elevatorInfo.elevatorName }}</view>
    <view f-s-c mt-8>
      <up-icon name="map-fill" :size="24" :color="`${'#579BF7'}`" />
      <text text-28 font-400 ml-4>{{ elevatorInfo.elevatorAddress }}</text>
    </view>
  </view>

  <view px-28 mt-20 pb-30>
    <up-form
      ref="form"
      label-width="80"
      label-position="left"
      :model="model"
      :rules="rules"
    >
      <up-form-item label="工作选项" prop="workType" border-bottom>
        <text>维修</text>
      </up-form-item>
      <up-form-item
        label="维修类型"
        prop="planType"
        border-bottom
        @click="
          () => {
            showAction = true
            hideKeyboard()
          }
        "
      >
        <up-input
          v-model="model.planTypeName"
          disabled
          disabled-color="#ffffff"
          placeholder="请选择维修类型"
          border="none"
        />
        <template #right>
          <up-icon name="arrow-right" />
        </template>
      </up-form-item>
      <up-form-item
        label="期望时间"
        prop="expectTime"
        label-width="80"
        border-bottom
        @click="
          () => {
            showCalendar = true
            hideKeyboard()
          }
        "
      >
        <up-input
          v-model="model.expectTime"
          disabled
          disabled-color="#ffffff"
          placeholder="请选择期望时间"
          border="none"
        />
        <template #right>
          <up-icon name="arrow-right" />
        </template>
      </up-form-item>
      <template v-if="model.planType === 12">
        <up-form-item
          label="零部件名称"
          prop="partName"
          label-width="80"
          border-bottom
        >
          <up-input
            v-model="model.partName"
            placeholder="请输入"
            border="none"
          />
        </up-form-item>
        <up-form-item
          label="规格型号"
          prop="partModel"
          label-width="80"
          border-bottom
        >
          <up-input
            v-model="model.partModel"
            placeholder="请输入"
            border="none"
          />
        </up-form-item>
        <up-form-item
          label="数量"
          prop="partNum"
          label-width="80"
          border-bottom
        >
          <up-input
            v-model="model.partNum"
            type="number"
            placeholder="请输入"
            border="none"
          />
        </up-form-item>
        <up-form-item
          label="材料报价"
          prop="materialQuote"
          label-width="80"
          border-bottom
        >
          <up-input
            v-model="model.materialQuote"
            type="digit"
            placeholder="请输入"
            border="none"
          />
        </up-form-item>
        <up-form-item
          label="人工及杂费"
          prop="otherExpenses"
          label-width="80"
          border-bottom
        >
          <up-input
            v-model="model.otherExpenses"
            type="digit"
            placeholder="请输入"
            border="none"
          />
        </up-form-item>
        <up-form-item
          label="总预算"
          prop="totalBudget"
          label-width="80"
          border-bottom
        >
          <up-input
            v-model="model.totalBudget"
            disabled
            disabled-color="#ffffff"
            placeholder="请输入"
            border="none"
          />
        </up-form-item>
      </template>
      <template v-if="model.planType === 11">
        <up-form-item
          label="调整优化项目"
          prop="partName"
          label-width="80"
          border-bottom
        >
          <up-input
            v-model="model.partName"
            placeholder="请输入"
            border="none"
          />
        </up-form-item>
        <up-form-item
          label="费用"
          prop="materialQuote"
          label-width="80"
          border-bottom
        >
          <up-input
            v-model="model.materialQuote"
            type="digit"
            placeholder="请输入"
            border="none"
          />
        </up-form-item>
      </template>
      <up-form-item
        label="工作描述："
        prop="description"
        label-position="top"
        :border="`${'none'}`"
      >
        <view mt-10>
          <up-textarea
            v-model="model.description"
            placeholder="请输入工作描述"
            maxlength="300"
            count
            height="150"
          />
        </view>
      </up-form-item>
      <up-form-item
        label="维修前照片："
        prop="repairBeforeRecord"
        label-width="100"
        label-position="top"
        :border="`${'none'}`"
      >
        <view w-200 h-200 f-c-c mt-10>
          <up-upload
            :file-list="fileList"
            :max-count="1"
            :preview-full-image="true"
            @afterRead="afterRead"
            @delete="deletePic"
          />
        </view>
      </up-form-item>
    </up-form>

    <up-button
      type="primary"
      text="确认创建"
      custom-style="margin-top: 30px"
      @click="submit"
    />
  </view>

  <up-action-sheet
    :show="showAction"
    :actions="actions"
    title="维保类型"
    @close="showAction = false"
    @select="actionSelect"
  />

  <up-calendar
    :show="showCalendar"
    confirm-disabled-text="请选择日期"
    @confirm="calendarConfirm"
    @close="calendarClose"
  />
</template>
