<template>
  <view class="orderList">
    <!-- 头部筛选 -->
    <view class="orderList_header">
      <view class="orderList_header_item" @click="openPicker('gdState')">
        <text class="orderList_header_itemText">{{selectedGdState}}</text>
        <text class="pda pda-xiala"></text>
      </view>
      <view class="orderList_header_item" @click="openPicker('associationType')">
        <text class="orderList_header_itemText">{{selectedAssociationType}}</text>
        <text class="pda pda-xiala"></text>
      </view>
    </view>
    <!-- 列表 -->
    <view class="orderList_list">
      <view class="orderList_listItem" v-for="newOrder in newOrderList" :key="newOrder.id">
        <image class="ji" src="../../static/imgs/icon_ji.png" mode="widthFix"
          v-if="newOrder.emergencyType && newOrder.emergencyType.value == 2"></image>
        <image class="jiaji" src="../../static/imgs/icon_jiaji.png" mode="widthFix"
          v-if="newOrder.emergencyType && newOrder.emergencyType.value == 3"></image>
        <view class="orderList_listItem_header">
          <view class="orderList_listItem_header_title">
            <view class="associationType_icon" v-if="newOrder.isHalfInspect === 1"> 半 </view>
            <view class="associationType_icon" v-else-if="newOrder.taskType.associationType.value == 'specimen'">标
            </view>
            <view class="associationType_icon" v-else-if="newOrder.taskType.associationType.value == 'drugsBag'"> 药
            </view>
            <view class="associationType_icon" v-else-if="newOrder.taskType.associationType.value == 'specimenPlan'"> 巡
            </view>
            <view class="associationType_icon" v-else-if="newOrder.taskType.associationType.value == 'jPBag'"> 静 </view>
            <view class="associationType_icon" v-else-if="newOrder.taskType.associationType.value == 'inspect'"> 病
            </view>
            <view class="associationType_icon"
              v-else-if="newOrder.taskType.associationType.value == 'patientTransport'"> 病
            </view>
            <view class="associationType_icon" v-else-if="newOrder.taskType.associationType.value == 'other'"> 其
            </view>
            <view class="taskNameAndWorkerName">
              <text class="taskName">{{newOrder.isHalfInspect === 1? "半程陪检": newOrder.taskType.taskName}}</text>
              <text class="workerName"
                v-if="newOrder.patient &&(newOrder.taskType.associationType.value =='patientTransport' ||newOrder.taskType.associationType.value =='inspect')">-{{newOrder.patient.patientName}}</text>
            </view>
          </view>
          <text class="orderList_listItem_header_more"
            :class="newOrder.stateTextClass">{{newOrder.gdState.name }}</text>
        </view>
        <view class="orderList_listItem_item">
          <view class="orderList_listItem_item_content">
            <text class="orderList_listItem_item_name"
              v-if="newOrder.worker">{{newOrder.worker.name}}{{newOrder.worker.phone? "-" + newOrder.worker.phone: ""}}</text>
            <text class="orderList_listItem_item_name" v-else>暂未接单</text>
            <text class="orderList_listItem_item_time" v-if="newOrder.showCreateTime">{{newOrder.showCreateTime}}</text>
            <text class="orderList_listItem_item_time"
              v-else-if="newOrder.yyjdTime && newOrder.gdState.value == GDSTATE['定时预约']">{{newOrder.yyjdTime | formatDate('MM-dd HH:mm')}}</text>
          </view>
          <view class="orderList_listItem_item_btns" v-if="
          newOrder.gdState.value == GDSTATE['待抢单'] ||
          newOrder.gdState.value == GDSTATE['待接单'] ||
          newOrder.gdState.value == GDSTATE['待到达'] ||
          newOrder.gdState.value == GDSTATE['定时预约'] ||
          newOrder.gdState.value == GDSTATE['待评价']
          ">
            <button type="primary" class="btn" v-if="newOrder.gdState.value == GDSTATE['待评价']"
              @click="showAppraise(newOrder.id)">评价</button>
            <button type="primary" class="btn" v-if="
            newOrder.gdState.value == GDSTATE['待抢单'] ||
            newOrder.gdState.value == GDSTATE['待接单'] ||
            newOrder.gdState.value == GDSTATE['待到达'] ||
            newOrder.gdState.value == GDSTATE['定时预约']
            " @click="openRecallModal(newOrder.id)">撤销</button>
            <button type="primary" class="btn" v-if="newOrder.gdState.value == GDSTATE['定时预约']"
              @click="openExecModal(newOrder.id)">立即执行</button>
            <button type="primary" class="btn" v-if="
            (newOrder.gdState.value == GDSTATE['待抢单'] ||
            newOrder.gdState.value == GDSTATE['待到达']) &&
            newOrder.taskType.allowUrgent == 1 &&
            !newOrder.urgentDetails
            " @click="showJiaji(newOrder.id)">加急</button>
          </view>
        </view>
      </view>
    </view>
    <seiminFooterNav></seiminFooterNav>
    <seiminModel ref="seiminModel"></seiminModel>
    <seiminPicker ref="sPicker" titleColor="#808080" titleFontSize="28rpx" confirmColor="#333" confirmFontSize="38rpx"
      confirmFontWeight="500" itemFontSize="28rpx" @onClose="closePicker" @onConfirm="confirmPicker"
      :pickerList="pickerList">
    </seiminPicker>
  </view>
</template>

<script>
  import {
    mapState,
    mapActions
  } from "vuex";
  import {
    reqFetchDataList,
    reqDelWorkOrder,
    reqUrge,
    reqDirectStartOrder,
    reqEvaluate,
  } from "../../request/api.js";
  import {
    GDSTATE
  } from "../../utils/enum.gdstate.js";
  import {
    WORKORDEREVALUATION
  } from "../../utils/enum.workorderEvaluation.js";
  export default {
    name: 'orderList',
    data() {
      return {
        // 工单状态
        GDSTATE: GDSTATE,
        // 当前筛选的工单状态
        selectedGdState: '执行中',
        // 当前筛选的关联类型
        selectedAssociationType: '全部',
        //工单状态筛选列表
        gdStates: [{
            value: -1,
            label: '全部'
          },
          {
            value: 1,
            label: '执行中'
          },
          {
            value: 2,
            label: '待评价'
          },
        ],
        //关联类型筛选列表
        associationTypes: [{
          value: -1,
          label: '全部'
        }, ],
        newOrderList: [], //工单列表
        totalNum: 0, //工单总数量
        idx: 0, //页码
        pageNum: 20, //每页的工单数量
        pickerList: [], //picker列表
        type: '', //打开picker的类型，工单状态||关联类型
        checkStatus: {}, //审核状态列表
      };
    },
    computed: {
      ...mapState("login", ["loginInfo"]),
    },
    methods: {
      ...mapActions("dictionary", ["vxDictionary"]),
      //评价
      showAppraise(id) {
        this.$refs.seiminModel.show({
          skin: 'evaluate',
          content: "工单已完成，请对本次服务做出评价！",
          btns: [{
              click: () => {
                console.log('取消');
                this.$refs.seiminModel.close();
              }
            },
            {
              click: () => {
                console.log('确定');
                let serviceEvaluationId;
                this.$refs.seiminModel.close();
                uni.showLoading({
                  title: '加载中',
                  mask: true,
                })
                //算出评级
                switch (this.$refs.seiminModel.stars.indexOf('pda-haoping1')) {
                  case -1:
                    //五星
                    serviceEvaluationId = WORKORDEREVALUATION['非常好评'];
                    break;
                  case 1:
                    //一星
                    serviceEvaluationId = WORKORDEREVALUATION['极差'];
                    break;
                  case 2:
                    //二星
                    serviceEvaluationId = WORKORDEREVALUATION['差'];
                    break;
                  case 3:
                    //三星
                    serviceEvaluationId = WORKORDEREVALUATION['一般'];
                    break;
                  case 4:
                    //四星
                    serviceEvaluationId = WORKORDEREVALUATION['好评'];
                    break;
                }
                let postData = {
                  serviceEvaluation: {
                    id: serviceEvaluationId
                  },
                  remark: this.$refs.seiminModel.evaluateTextArea,
                };
                reqEvaluate(id, postData).then(res => {
                  uni.hideLoading();
                  if (res.status == 200) {
                    this.$refs.seiminModel.show({
                      skin: 'toast',
                      icon: 'success',
                      content: '评价成功',
                    })
                    this.init();
                  } else {
                    this.$refs.seiminModel.show({
                      skin: 'toast',
                      icon: 'error',
                      content: '评价失败',
                    })
                  }
                })
              }
            }
          ]
        });
      },
      //撤销
      openRecallModal(id) {
        this.$refs.seiminModel.show({
          icon: "warn",
          content: "您确认要撤销工单吗？撤销工单我们会通知服务台、支助人员不再执行此工单，请谨慎操作，如确认撤销请点击确认。",
          btns: [{
              click: () => {
                console.log('取消');
                this.$refs.seiminModel.close();
              }
            },
            {
              click: () => {
                console.log('确定');
                this.$refs.seiminModel.close();
                uni.showLoading({
                  title: '加载中',
                  mask: true,
                })
                reqDelWorkOrder(id).then(res => {
                  uni.hideLoading();
                  if (res.status == 200) {
                    this.$refs.seiminModel.show({
                      skin: 'toast',
                      icon: 'success',
                      content: '撤销成功',
                    })
                    this.init();
                  } else {
                    this.$refs.seiminModel.show({
                      skin: 'toast',
                      icon: 'error',
                      content: '撤销失败',
                    })
                  }
                })
              }
            }
          ]
        });
      },
      //立即执行
      openExecModal(id) {
        this.$refs.seiminModel.show({
          icon: 'warn',
          content: '您确认要立即执行该工单吗？',
          btns: [{
            click: () => {
              console.log('取消');
              this.$refs.seiminModel.close();
            }
          }, {
            click: () => {
              console.log('确认');
              this.$refs.seiminModel.close();
              uni.showLoading({
                title: '加载中',
                mask: true,
              })
              reqDirectStartOrder(id).then(res => {
                uni.hideLoading();
                if (res.status == 200) {
                  this.$refs.seiminModel.show({
                    skin: 'toast',
                    icon: 'success',
                    content: '您的加急申请已成功，调度人员会紧急处理！',
                  })
                  this.init();
                } else {
                  this.$refs.seiminModel.show({
                    skin: 'toast',
                    icon: 'error',
                    content: '加急失败',
                  })
                }
              })
            }
          }, ]
        })
      },
      //加急
      showJiaji(id) {
        this.$refs.seiminModel.urgentTextArea = '';
        this.$refs.seiminModel.show({
          title: '',
          skin: 'urgent',
          content: "请填写加急原因，填写后我们会根据您的诉求优先处理",
          btns: [{
              click: () => {
                console.log('取消');
                this.$refs.seiminModel.close();
              }
            },
            {
              click: () => {
                console.log('确定', this.$refs.seiminModel.urgentTextArea);
                const urgentTextArea = this.$refs.seiminModel.urgentTextArea;
                if (urgentTextArea.trim() === '') {
                  uni.showToast({
                    icon: 'none',
                    title: '请填写加急原因',
                  })
                  return;
                }
                this.$refs.seiminModel.close();
                uni.showLoading({
                  title: '加载中',
                  mask: true,
                })
                let postData = {
                  urgentDetails: {
                    workerOrder: id,
                    checkStatus: {
                      id: this.checkStatus[1]
                    },
                    urgentReason: urgentTextArea,
                  },
                };
                reqUrge(postData).then(res => {
                  uni.hideLoading();
                  if (res.status == 200) {
                    this.$refs.seiminModel.show({
                      skin: 'toast',
                      icon: 'success',
                      content: '加急成功',
                    })
                    this.init();
                  } else {
                    this.$refs.seiminModel.show({
                      skin: 'toast',
                      icon: 'error',
                      content: '加急失败',
                    })
                  }
                })
              }
            }
          ]
        });
      },
      //关闭
      closePicker() {
        this.$refs.sPicker._close();
      },
      //打开
      openPicker(type) {
        this.type = type;
        this.$refs.sPicker._open();
        if (type === 'gdState') {
          //工单状态
          this.pickerList = this.gdStates;
          let index = this.pickerList.findIndex(v => v.label === this.selectedGdState);
          let obj = this.pickerList.find(v => v.label === this.selectedGdState);
          this.$refs.sPicker._changeValue(index);
          this.selectedGdState = obj && obj.label;
        } else if (type === 'associationType') {
          //关联类型
          this.pickerList = this.associationTypes;
          let index = this.pickerList.findIndex(v => v.label === this.selectedAssociationType);
          let obj = this.pickerList.find(v => v.label === this.selectedAssociationType);
          this.$refs.sPicker._changeValue(index);
          this.selectedAssociationType = obj && obj.label;
        }
      },
      //确定：接收子组件传来的参数
      confirmPicker(checkedObj) {
        if (this.type === 'gdState') {
          //工单状态
          this.selectedGdState = checkedObj.label;
        } else if (this.type === 'associationType') {
          //关联类型
          this.selectedAssociationType = checkedObj.label;
        }
        let index = this.pickerList.findIndex(v => v.label === checkedObj.label);
        this.$refs.sPicker._changeValue(index);
        this.init();
      },
      // 获取页面数据
      init() {
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        Promise.all([
          this.queryWorkOrdersRequest(), //查询最新工单列表
          this.queryDictionary('association_types'), //获取数据字典-关联类型
          this.queryDictionary('check_status'), //获取数据字典-审核状态
        ]).then((values) => {
          uni.hideLoading();
          uni.stopPullDownRefresh();
          this.queryWorkOrdersResponse(values[0]);
          this.queryDictionaryResponse(values[1], 'association_types');
          this.queryDictionaryResponse(values[2], 'check_status');
        });
      },
      // 查询最新工单列表（上拉）
      reachBottom() {
        //没有更多
        if (this.newOrderList.length == this.totalNum) {
          uni.showToast({
            icon: 'none',
            title: '没有更多工单了'
          })
          return;
        }
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        Promise.all([
          this.queryWorkOrdersRequest(true), //查询最新工单列表
        ]).then((values) => {
          uni.hideLoading();
          this.queryWorkOrdersResponse(values[0], true);
        });
      },
      // 查询最新工单列表
      queryWorkOrdersRequest(idxPlus = false) {
        console.log(this.selectedGdState, this.selectedAssociationType);
        console.log(this.gdStates, this.associationTypes);
        if (idxPlus) {
          //累加
          ++this.idx;
        } else {
          this.idx = 0;
        }
        let postData = {
          workOrder: {
            createDept: this.loginInfo.user.dept.id,
            platform: 2,
            searchDays: 2,
          },
          idx: this.idx,
          sum: this.pageNum,
        };
        let selectedGdStateValue = this.gdStates.find(v => v.label == this.selectedGdState).value;
        let associationTypesValue = this.associationTypes.find(v => v.label == this.selectedAssociationType).value;
        // 工单状态
        // 执行中包含状态：待抢单、待接单、待到达、待送达、执行中、定时预约
        if (selectedGdStateValue == 1) {
          // 执行中
          postData.workOrder.nurseState = 1;
        } else if (selectedGdStateValue == 2) {
          // 待评价
          postData.workOrder.gdState = {
            id: "73"
          };
        }
        //关联类型
        if (associationTypesValue != -1) {
          postData.workOrder.taskType = {
            associationType: {
              id: associationTypesValue,
            }
          }
        }
        return reqFetchDataList("nurse", "workOrder", postData);
      },
      // 查询最新工单列表
      queryWorkOrdersResponse(res, idxPlus = false) {
        if (res.status == 200) {
          res.list = res.list || [];
          this.totalNum = res.totalNum || 0;
          let newOrderList = res.list.map((v) => {
            if (v.gdState) {
              if (
                v.gdState.value == GDSTATE["待接单"] ||
                v.gdState.value == GDSTATE["待抢单"]
              ) {
                v.stateTextClass = "red";
              } else if (
                v.gdState.value == GDSTATE["待评价"] ||
                v.gdState.value == GDSTATE["已完成"]
              ) {
                v.stateTextClass = "green";
              } else {
                v.stateTextClass = "yellow";
              }
            }
            return v;
          });
          if (idxPlus) {
            //累加
            this.newOrderList = this.newOrderList.concat(newOrderList);
          } else {
            this.newOrderList = newOrderList;
          }
        } else {
          this.$refs.seiminModel.show({
            skin: "toast",
            icon: "error",
            content: res.msg || "获取数据失败",
          });
          throw new Error(res.msg || '获取数据失败');
        }
      },
      // 获取数据字典
      queryDictionary(key) {
        let postData = {
          "type": "list",
          key
        };
        return this.vxDictionary(postData);
      },
      // 获取数据字典
      queryDictionaryResponse(res, type) {
        let obj = {};
        let arr = [];
        switch (type) {
          case 'association_types':
            arr = res.map(v => ({
              value: v.id,
              label: v.name
            }));
            this.associationTypes = [{
              label: '全部',
              value: -1
            }, ...arr];
            break;
          case 'check_status':
            obj = {};
            res.forEach(v => {
              obj[v.value] = v.id;
            })
            this.checkStatus = obj;
            break;
        }
      },
    },
    mounted() {
      this.init();
    },
    onPullDownRefresh() {
      this.init();
    },
    onReachBottom() {
      this.reachBottom();
    }
  }
</script>

<style lang="scss" scoped>
  .orderList {
    padding-bottom: 108rpx;

    // 头部筛选
    .orderList_header {
      height: 88rpx;
      background-color: #fff;
      border-bottom: 1px solid #E5E9ED;
      position: fixed;
      left: 0;
      z-index: 99;
      width: 100%;
      @include flex(center, center);

      .orderList_header_item {
        flex: 1;
        height: 100%;
        padding: 0 50rpx;
        border-right: 1px solid #E5E9ED;
        @include flex(space-between, center);

        &:last-of-type {
          border-right: none;
        }

        .orderList_header_itemText {
          color: #333;
          font-size: 38rpx;
        }

        .pda-xiala {
          color: #DDE1E5;
        }
      }
    }

    // 列表
    .orderList_list {
      padding: 88rpx 24rpx 0;

      .orderList_listItem {
        width: 702rpx;
        min-height: 320rpx;
        background-color: #fff;
        margin-top: 8rpx;
        border-radius: 8rpx;
        border: 2rpx solid #e5e9ed;
        position: relative;
        padding: 0 24rpx;
        font-size: 32rpx;
        @include semicircle(#f9fafb, 82rpx);
        @include flex(flex-start, stretch, column);

        .ji,
        .jiaji {
          width: 60rpx;
          position: absolute;
          right: 0;
          top: 0;
        }

        .orderList_listItem_header {
          height: 86rpx;
          border-bottom: 2rpx dashed #e5e9ed;
          @include flex(space-between, center);

          .orderList_listItem_header_title {
            color: #333;
            flex: 1;
            @include flex(flex-start, center);

            .associationType_icon {
              width: 48rpx;
              height: 48rpx;
              border-radius: 50%;
              background-color: #F0F6ED;
              border: 1px solid #39b199;
              font-size: 24rpx;
              color: #39b199;
              margin-right: 8rpx;
              @include flex(center, center);
            }

            .taskNameAndWorkerName {
              flex: 1;
              @include flex;

              .taskName {
                max-width: 10em;
                @include clamp;
              }

              .workerName {
                flex: 1;
                @include clamp;
              }
            }
          }

          .orderList_listItem_header_more {
            color: #666;
          }
        }

        .orderList_listItem_item {
          height: 88rpx;
          border-bottom: 1px solid #e5e9ed;
          color: #333;
          font-size: 30rpx;
          flex: 1;
          @include flex(flex-start, stretch, column);

          &:last-of-type {
            border-bottom: none;
          }

          .orderList_listItem_item_content {
            min-height: 143rpx;
            flex: 1;
            @include flex(space-between, center);

            .orderList_listItem_item_name {
              font-size: 38rpx;
              font-weight: bold;
            }

            .orderList_listItem_item_time {
              color: #666;
              font-size: 28rpx;
            }
          }

          .orderList_listItem_item_btns {
            position: relative;
            left: -24rpx;
            width: 698rpx;
            height: 88rpx;
            @include btn_background;
            @include flex;

            .btn {
              flex: 1;
              background-color: transparent;
              position: relative;
              @include flex(center, center);

              &::before {
                content: '';
                position: absolute;
                right: 0;
                top: 0;
                width: 2rpx;
                height: 100%;
                border-right: 2rpx solid #fff;
              }

              &:last-of-type::before {
                border-right: none;
              }

              &::after {
                border: none;
              }
            }
          }
        }
      }
    }
  }
</style>
