<template>
  <view class="work-order-wrap info-wrap">
    <panel>
      <template v-slot:header>
        <up-icon size="28rpx" :name="list"></up-icon>
        工单信息
      </template>
      <template v-slot:content>
        <view class="order-info" style="width: 100%">
          <view class="mix-wrap">
            <view class="info-column">
              <label-text
                  label="工单类型"
                  :text="valueToConst(WorkOrderTypes,state.orderInfo.type).label"
              />
              <label-text
                  label="工单号"
                  :line="2"
                  :text="state.orderInfo.code"
              />
              <label-text
                  label="紧急程度"
                  :text="valueToConst(WorkOrderLevel,state.orderInfo.status).label"
              />
              <label-text
                  label="是否逾期"
                  :text="getDeviceStatus(state.orderInfo)"
              />
            </view>
            <images-h :url="state.orderInfo.problemImgSingle"/>
          </view>
          <view class="line-info-wrap">
            <label-text
                label="预计处理时间"
                :text="state.orderInfo.estimatedStartTime"
            />
            <label-text
                label="预计结束时间"
                :text="state.orderInfo.estimatedEndTime"
            />
            <label-text
                label="问题原因"
                :line="2"
                :text="formatTxt(state.orderInfo.reason)"
            />
            <label-text
                label="解决方案"
                :line="2"
                :text="formatTxt(state.orderInfo.solution)"
            />
            <label-text
                label="费用/材料"
                :line="1"
                :text="formatTxt(state.orderInfo.consumables)"
            />
            <label-text
                label="是否需要补充材料"
                :text="state.orderInfo.rewrite ? '是': '否'"
            />
            <label-text
                v-if="state.orderInfo.rewrite"
                label="补充材料说明"
                :line="3"
                :text="formatTxt(state.orderInfo.rewriteDes)"
            />
            <label-text
                label="描述"
                :line="3"
                :text="formatTxt(state.orderInfo.description)"
            />
          </view>
        </view>
      </template>
    </panel>
    <panel v-if="state.orderInfo.problemImg && state.orderInfo.problemImg.length>0">
      <template v-slot:header>
        <up-icon size="28rpx" :name="list"></up-icon>
        问题图片
      </template>
      <template v-slot:content>
        <view>
          <up-album :urls="state.orderInfo.problemImg" :autoWrap="true" :maxCount="8"></up-album>
        </view>
      </template>
    </panel>
    <panel v-if="state.orderInfo.solveImg && state.orderInfo.solveImg.length>0">
      <template v-slot:header>
        <up-icon size="28rpx" :name="list"></up-icon>
        处置图
      </template>
      <template v-slot:content>
        <view>
          <up-album :urls="state.orderInfo.solveImg" :autoWrap="true" :maxCount="8"></up-album>
        </view>
      </template>
    </panel>
    <panel v-if="state.steps.length>0">
      <template v-slot:header>
        <up-icon size="28rpx" :name="list"></up-icon>
        工单历程
      </template>
      <template v-slot:content>
        <steps
            :orientation="'vertical'"
            :steps="state.steps"
            style="width: 100%"
        >
          <template #stepTitle="props">
            <view class="title-info">{{ props.stepInfo.username }}</view>
            <view class="title-date">{{ props.stepInfo.handleTime }}</view>
          </template>
          <template #stepItem="props">
            <view class="step-content">
              由{{ props.stepInfo.username }} &nbsp;{{ getStepInfo(props.stepInfo).content }}

            </view>
          </template>
        </steps>
      </template>
    </panel>
    <up-tabbar
        :fixed="true"
        :placeholder="false"
        :safeAreaInsetBottom="false"
    >
      <template v-if="state.orderInfo.rewrite">
        <view class="def-btn"
              @click="state.showDisableModal = true">
          补充材料
        </view>
      </template>
      <template v-else>
        <view
            class="warning-btn"
            v-if="[WorkOrderStat.UN_HANDLE.value].includes(state.orderInfo.status )"
            @click="state.showDisableModal=true"
        >
          作废
        </view>
        <view
            class="def-btn"
            v-if="[WorkOrderStat.IN_HANDLE.value].includes(state.orderInfo.status )"
            @click="state.handleForm = true"
        >
          处理
        </view>
        <view
            class="def-btn"
            v-if="[WorkOrderStat.UN_HANDLE.value,WorkOrderStat.IN_HANDLE.value].includes(state.orderInfo.status )"
            @click="state.toUsrShow=true;state.toUsrCb = assignWorkOrderCb;"
        >
          指派
        </view>
        <view
            class="def-btn"
            v-if="[WorkOrderStat.UN_HANDLE.value].includes(state.orderInfo.status )"
            @click="state.showAcceptModal=true"
        >
          受理
        </view>
      </template>
    </up-tabbar>
    <up-modal
        :show="state.showDisableModal"
        title="确认作废"
        :closeOnClickOverlay="true"
        :showCancelButton="true"
        @close="state.showDisableModal = false"
        @cancel="state.showDisableModal = false"
        @confirm="onConfirmDisable"
    >
      <view class="modal-content">
        确定作废这个工单？
      </view>
    </up-modal>
    <up-modal
        :show="state.showAcceptModal"
        title="确认受理"
        :closeOnClickOverlay="true"
        :showCancelButton="true"
        @close="state.showAcceptModal = false"
        @cancel="state.showAcceptModal = false"
        @confirm="onConfirmAccept"
    >
      <view class="modal-content">
        确定受理这个工单？
      </view>
    </up-modal>
    <up-action-sheet
        :show="state.handleForm"
        @close="state.handleForm = false"
        title="处理工单"
        :round="10"
    >
      <view class="action-content common-form">
        <up-form
            labelPosition="left"
            :model="state.model"
            :rules="state.rules"
            ref="formRef"
            labelWidth="120"
        >
          <up-form-item
              label="工单名称"
              borderBottom
              :required="true"
          >
            <up-input
                :modelValue="state.orderInfo.name"
                border="none"
                disabled
            ></up-input>
          </up-form-item>
          <up-form-item
              label="产生原因"
              borderBottom
          >
            <up-input
                v-model="state.model.order.reason"
                border="none"
            ></up-input>
          </up-form-item>
          <up-form-item
              label="解决方案"
              borderBottom
          >
            <up-input
                v-model="state.model.order.solution"
                border="none"
            ></up-input>
          </up-form-item>
          <up-form-item
              label="费用/材料"
              borderBottom
          >
            <up-input
                v-model="state.model.order.consumables"
                border="none"
            ></up-input>
          </up-form-item>
          <up-form-item
              label="是否已解决"
              borderBottom
          >
            <up-switch v-model="state.model.order.isSolve"></up-switch>
          </up-form-item>
          <up-form-item
              v-if="!state.model.order.isSolve"
              label="是否补充材料"
              borderBottom
          >
            <up-switch v-model="state.model.order.rewrite"></up-switch>
          </up-form-item>
          <up-form-item
              label="处理人"
              v-if="state.model.order.rewrite && !state.model.order.isSolve"
              borderBottom
              @click="state.toUsrShow = true;state.toUsrCb = rewriteWorkOrderCb; hideKeyboard()"
          >
            <up-input
                disabled
                :modelValue="state.model.order.handleUser2"
                disabledColor="#ffffff"
                placeholder="其请选择处理人"
                border="none"
            ></up-input>
            <template #right>
              <up-icon
                  name="arrow-right"
              ></up-icon>
            </template>
          </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="endWorkOrderHandle" style="margin-top: 20rpx;">提交</up-button>
        </up-form>
      </view>
    </up-action-sheet>
    <up-toast ref="uToastRef"></up-toast>
    <up-action-sheet
        :show="state.toUsrShow"
        @close="state.toUsrShow = false"
        title="选择指派对象"
        :round="10"
    >
      <view class="action-content common-form">
        <DaTree
            ref="DaTreeRef"
            :data="roomTreeData"
            labelField="name"
            valueField="id"
            defaultExpandAll
            :defaultCheckedKeys="defaultCheckedKeysValue"
        />
        <up-button @click="()=>confirmToUsr(state.toUsrCb)" style="margin-top: 20rpx;">指派</up-button>
      </view>
    </up-action-sheet>
    <overlay-tip ref="overlay"/>
  </view>
</template>

<script setup lang="ts">

import list from "@/static/aiot/list.svg";
import Panel from "@/components/pannel/index.vue";
import LabelText from "@/components/labeltext/index.vue";
import Steps from "@/components/steps/index.vue";
import OverlayTip from "@/components/overlay-tip/index.vue";
import {onMounted, reactive, ref, watch} from 'vue';

import {onLoad} from "@dcloudio/uni-app";
import {
  assignWorkOrder,
  endWorkOrder,
  getWorkOrderDetail,
  getWorkOrderSteps,
  handleWorkOrder,
  scrapWorkOrder,
  uploadOrderFile
} from "@/api/workorder.js";
import {qryUserInfo} from "@/api/usr.js";
import {valueToConst} from "@/common/consts/CommonConst.js";
import {WorkOrderLevel, WorkOrderStat, WorkOrderTypes} from "@/common/consts/WorkOrderConst.js";
import {formatTxt, getImgs, getStepInfo, hideKeyboard} from "@/util/index.js";
import ImagesH from "@/components/imagesh/index.vue";
import DaTree from '@/components/da-tree/index.vue';

const order = ref('')
const DaTreeRef = ref(null)
const overlay = ref(null)
// key的类型必须对应树数据key的类型
const defaultCheckedKeysValue = ref(['211', '222'])
const roomTreeData = ref([])

const state = reactive({
  showDisableModal: false,
  showAcceptModal: false,
  handleForm: false,
  toUsrShow: false,
  orderInfo: {
    problemImg: [],
    solveImg: []
  },
  model: {
    order: {
      isSolve: true,
      rewrite: false,
      files: []
    }
  },
  steps: []
})
const uToastRef = ref(null)
onLoad((option) => {
  order.value = option.id
});
onMounted(() => {
  refresh()
})
watch(() =>
    state.toUsrShow, (newVal) => {
  if (newVal) {
    qryUserInfo({currentPage: 1, pageSize: 100}).then((data) => {
      if (data && data.records) {
        const {records} = data;
        const groupTemp = {}
        records.forEach((item) => {
          let dept = item.dept;
          if (!item.dept) {
            dept = '其他'
          }
          if (!groupTemp[dept]) {
            groupTemp[dept] = {
              id: dept,
              name: dept,
              children: [],
            }
          }
          groupTemp[dept].children.push({
            id: item.id,
            name: item.nickname,
            children: null,
            dataNode: true
          })
        })
        roomTreeData.value = Object.values(groupTemp)
      }
    })
  }
})
const refresh = () => {
  getWorkOrderDetail(order.value).then((data) => {
    state.orderInfo = data
    state.orderInfo.statusMsg = getDeviceStatus(data)
    data.problemImg && (state.orderInfo.problemImg = getImgs(data.problemImg))
    data.solveImg && (state.orderInfo.solveImg = getImgs(data.solveImg))
    state.orderInfo.problemImgSingle = state.orderInfo.problemImg
        && state.orderInfo.problemImg.length > 0
        && state.orderInfo.problemImg[0]
  })
  getWorkOrderSteps(order.value).then((data) => {
    state.steps = data
  })
}
const assignWorkOrderCb = () => {
  overlay.value.load({})
  assignWorkOrder({
    handleUser: DaTreeRef.value.getCheckedNodes()[0].key,
    id: order.value
  }).then(() => {
    state.toUsrShow = false;
    uToastRef.value.show({
      type: 'default',
      message: "操作成功",
      complete() {
        uni.$emit('refreshData', {refresh: true});
        uni.navigateBack({
          delta: 1
        })
      }
    })
  }).finally(() => {
    overlay.value.end()
  })
}

const endWorkOrderHandle = () => {
  endWorkOrder({
    ...state.model.order,
    img: JSON.stringify(state.model.order.files),
    solveImg: JSON.stringify(state.model.order.files),
    id: order.value
  }).then(() => {
    uToastRef.value.show({
      type: 'default',
      message: "操作成功",
      complete() {
        uni.$emit('refreshData', {refresh: true});
        uni.navigateBack({
          delta: 1
        })
      }
    });
  })
}

const rewriteWorkOrderCb = () => {
  const selectNode = DaTreeRef.value.getCheckedNodes()[0]
  state.model.order.handleUser = selectNode.key;
  state.model.order.handleUser2 = selectNode.label;
  state.toUsrShow = false;
}
const confirmToUsr = (cb = () => {
}) => {
  if (!DaTreeRef.value || !DaTreeRef.value.getCheckedNodes() || DaTreeRef.value.getCheckedNodes().length === 0) {
    uToastRef.value.show({
      type: 'warning',
      message: "请选择处理人",
    })
    return;
  }
  cb();
}
const getDeviceStatus = (dataDetail) => {
  let statusMsg = []
  if (dataDetail.status === 1 && isLessThanNow(dataDetail.estimatedStartTime)) {
    statusMsg.push('处理逾期')
  }
  if ((dataDetail.status === 1 || dataDetail.status === 2) && isLessThanNow(dataDetail.estimatedEndTime)) {
    statusMsg.push('结束逾期')
  }
  return statusMsg.join('、')
}
const isLessThanNow = (date) => {
  let str1 = new Date(date).getTime();
  let str2 = new Date().getTime();
  // 小于0则str1时间小，大于0则str1时间大
  return str1 - str2 < 0
}
const onConfirmDisable = () => {
  scrapWorkOrder(order.value).then(() => {
    state.handleForm = false;
    uToastRef.value.show({
      type: 'default',
      message: "操作成功",
      complete() {
        uni.$emit('refreshData', {refresh: true});
        uni.navigateBack({
          delta: 1
        })
      }
    });
  })
}
const onConfirmAccept = () => {
  handleWorkOrder(order.value).then(() => {
    state.showAcceptModal = false;
    uToastRef.value.show({
      type: 'default',
      message: "操作成功",
      complete() {
        refresh()
      }
    });
  })
}
const deletePic = (event) => {
  state.model.order.files.splice(event.index, 1)
}
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++
  }
}
</script>


<style lang="scss">
.work-order-wrap {
  padding-bottom: 140rpx;

  .panel-wrap {
    margin-bottom: $uni-block-gap;
  }

  .mix-wrap {
    display: flex;
    align-items: center;
    justify-content: center;

    .info-column {
      display: flex;
      flex: 1;
      align-items: flex-start;
      justify-content: flex-start;
      flex-direction: column;
    }
  }

  .panel-content {
    box-sizing: border-box;
    padding: 15px 15px 15px 15px;
  }

  .label-text-wrap {
    margin-top: $uni-text-gap;
  }

  .stepper-container {
    .title-date {
      margin-left: auto;
    }
  }

  .u-tabbar__content__item-wrapper {
    padding-bottom: 40rpx;


    > view {
      box-sizing: border-box;
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      color: $uni-bg-color;

      &:not(:last-child) {
        border-right: 2rpx solid #fefefe47;
      }
    }

    .warning-btn {
      background-color: $uni-color-error;
    }

    .def-btn {
      background-color: $uni-color-primary;
    }
  }

  .action-content {
    padding: 0 $uni-pop-padding;
  }

}


</style>
