<template>
  <view class="order-form info-wrap common-form">
    <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
    <up-form
        labelPosition="left"
        :model="state.model"
        :rules="state.rules"
        ref="formRef"
        labelWidth="120"
    >
      <up-form-item
          label="工单名称"
          prop="order.name"
          borderBottom
          :required="true"
      >
        <up-input
            v-model="state.model.order.name"
            border="none"
        ></up-input>
      </up-form-item>
      <up-form-item
          label="工单类型"
          prop="order.type"
          borderBottom
          :required="true"
          @click="state.showOrderType = true; hideKeyboard()"
      >
        <up-input
            :modelValue="valueToConst(WorkOrderTypes, state.model.order.type).label"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择工单类型"
            :required="true"
            border="none"
        ></up-input>
        <template #right>
          <up-icon
              name="arrow-right"
          ></up-icon>
        </template>
      </up-form-item>
      <up-form-item
          label="工单等级"
          prop="order.level"
          borderBottom
          :required="true"
          @click="state.showOrderLevel = true; hideKeyboard()"
      >
        <up-input
            :modelValue="valueToConst(WorkOrderLevel, state.model.order.level).label"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择工单等级"
            border="none"
        ></up-input>
        <template #right>
          <up-icon
              name="arrow-right"
          ></up-icon>
        </template>
      </up-form-item>
      <up-form-item
          label="预计开始日期"
          prop="order.startDate"
          borderBottom
          :required="true"
          @click="state.showStartClendar = true; hideKeyboard()"
      >
        <up-input
            :modelValue="formatDate(state.model.order.startDate)"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择预计开始日期"
            border="none"
        ></up-input>
        <template #right>
          <up-icon
              name="arrow-right"
          ></up-icon>
        </template>
      </up-form-item>
      <up-form-item
          label="预计结束日期"
          prop="order.endDate"
          borderBottom
          :required="true"
          @click="state.showEndClendar = true; hideKeyboard()"
      >
        <up-input
            :modelValue="formatDate(state.model.order.endDate)"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择预计结束日期"
            border="none"
        ></up-input>
        <template #right>
          <up-icon
              name="arrow-right"
          ></up-icon>
        </template>
      </up-form-item>
      <up-form-item
          label="故障描述"
          borderBottom
      >
        <up-textarea
            placeholder="故障描述"
            v-model="state.model.order.desc"
        ></up-textarea>
      </up-form-item>
      <up-form-item>
        <text class="u-demo-block__title">问题图片</text>
        <up-upload
            :fileList="state.model.order.files"
            @afterRead="afterRead"
            @delete="deletePic"
            name="imags"
            multiple
            :maxCount="5"
            :previewFullImage="true"
        ></up-upload>
      </up-form-item>
      <up-button @click="submit" style="margin-top: 20rpx;">提交</up-button>
    </up-form>
    <up-action-sheet
        :show="state.showOrderType"
        :actions="state.orderTypeList"
        title="请选择工单类型"
        @close="state.showOrderType = false"
        @select="orderTypeSelect"
    >
    </up-action-sheet>
    <up-action-sheet
        :show="state.showOrderLevel"
        :actions="state.orderLevelList"
        title="请选择工单等级"
        @close="state.showOrderLevel = false"
        @select="orderLevelSelect"
    >
    </up-action-sheet>
    <up-datetime-picker
        :show="state.showStartClendar"
        v-model="state.model.order.startDate"
        mode="datetime"
        @close="state.showStartClendar = false"
        :closeOnClickOverlay="true"
        @confirm="(e)=>confirm(e,'showStartClendar')"
        @cancel="state.showStartClendar = false"
    ></up-datetime-picker>
    <up-datetime-picker
        :show="state.showEndClendar"
        v-model="state.model.order.endDate"
        mode="datetime"
        @close="state.showEndClendar = false"
        :closeOnClickOverlay="true"
        @confirm="(e)=>confirm(e,'showEndClendar')"
        @cancel="state.showEndClendar = false"
    >
    </up-datetime-picker>
  </view>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue'
import {submitOrderWork, uploadOrderFile} from '@/api/workorder.js'
import dayjs from 'dayjs';
import {DateFormat, hideKeyboard, reloadPage, timestampToDate} from "@/util/index.js";
import {WorkOrderLevel, WorkOrderTypes} from "@/common/consts/WorkOrderConst.js";
import {valueToConst} from "@/common/consts/CommonConst.js";

const state = reactive({
  showOrderType: false,
  showOrderLevel: false,
  showStartClendar: false,
  showEndClendar: false,
  model: {
    order: {
      files: [],
      startDate: dayjs().valueOf(),
      endDate: dayjs().valueOf(),
    }
  },
  orderTypeList: [],
  orderLevelList: [],
  rules: {
    'order.name': {
      type: 'string',
      required: true,
      message: '请填工单名称',
      trigger: ['blur', 'change'],
    },
    'order.type': {
      type: 'number',
      required: true,
      message: '请选择工单类型',
      trigger: ['blur', 'change'],
    },
    'order.level': {
      type: 'number',
      required: true,
      message: '请选择工单等级',
      trigger: ['blur', 'change'],
    },
    'order.startDate': {
      type: 'number',
      required: true,
      message: '请选择预计开始时间',
      trigger: ['blur', 'change'],
    },
    'order.endDate': {
      type: 'number',
      required: true,
      message: '请选择预计结束时间',
      trigger: ['blur', 'change'],
    }
  },
});
Object.keys(WorkOrderTypes).forEach(key => {
  state.orderTypeList.push({name: WorkOrderTypes[key].label, id: WorkOrderTypes[key].value})
});
Object.keys(WorkOrderLevel).forEach(key => {
  state.orderLevelList.push({name: WorkOrderLevel[key].label, id: WorkOrderLevel[key].value})
});
// 使用 ref 创建响应式引用
const formRef = ref(null);

const orderTypeSelect = (item) => {
  state.model.order.type = item.id;
  state.showOrderType = false;
};
const orderLevelSelect = (item) => {
  state.model.order.level = item.id;
  state.showOrderLevel = false;
};

// 删除图片
const deletePic = (event) => {
  state.model.order.files.splice(event.index, 1)
}
const formatDate = (date) => {
  return timestampToDate(date)
}
const confirm = (e, type) => {
  state[type] = false;
};
const afterRead = async (event) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file)
  let fileListLen = state.model.order.files.length
  lists.map((item) => {
    state.model.order.files.push({
      ...item,
      status: 'uploading',
      message: '上传中'
    })
  })
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadOrderFile(lists[i].url)
    let item = state.model.order.files[fileListLen]
    state.model.order.files.splice(fileListLen, 1, Object.assign(item, {
      status: 'success',
      name: result.fileName,
      uid: result.md5,
      url: result.url
    }))
    fileListLen++
  }
}
const submit = () => {
  formRef.value.validate().then(async valid => {
    if (valid) {
      const order = state.model.order
      submitOrderWork({
        "name": order.name,
        "type": order.type,
        "level": order.level,
        "estimatedStartTime": dayjs(order.startDate).format(DateFormat.YYYYMMDDHHMMSS),
        "estimatedEndTime": dayjs(order.endDate).format(DateFormat.YYYYMMDDHHMMSS),
        "description": order.desc,
        "source": 2,
        "problemImg": JSON.stringify(order.files),
        "problemFile": null
      }).then(res => {
        uni.$u.toast('提交成功')
        reloadPage()
      })
    } else {
      uni.$u.toast('校验失败')
    }
  }).catch((e) => {
    // 处理验证错误
    uni.$u.toast('校验失败')
  });
}
</script>


<style lang="scss">
.order-form {
  background-color: #fff;
  border-radius: $uni-text-gap;
  padding: $uni-text-gap;
}
</style>
