<template>
  <!-- 待配送订单 -->
  <div class="home">
    <div ref="grabble">
      <actionBar :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm" @openModel="openModel"
        @searchProtocol="searchProtocol"></actionBar>
    </div>
    <div class="card_content">
      <!-- 表单 -->
      <tables ref="refWaybill" controlswidth="360px" tableHeight="68vh" :suspension="true" :tableList="tableList"
        :tableData="tableData" @buttonData="buttonData">
      </tables>
      <!-- 分页 -->
      <div v-if="Total">
        <pagination :total="Total" :currentPage="Pagination.PageIndex" @changeSize="changeSize"
          @changeCurrent="changeCurrent">
        </pagination>
      </div>
    </div>
    <orderDetails ref="order" :waybillData="waybillData"></orderDetails>
    <el-dialog title="分配订单" :visible.sync="sendDialogVisible" width="800px" :close-on-click-modal="false"
      @close="closeDialog">
      <forms ref="sendRules" :formNewList="sendRuleList" :ruleForm="sendRuleForm" :formIceTracing="true"
        :iceTracing="true" :iceBank="true" labelWidth="80px" @handleScroll="handleScroll" @remoteMethod="remoteMethod"
        @changeOption="changeOption">
      </forms>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="sendDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="sendConfirmLoading" @click.stop="sendHandleAdd">确 定</el-button>
      </span>
    </el-dialog>
    <prescriptionPicture ref="picture" :srcList="srcList" :fileList="fileList" :orderID="orderId"
      @prescription="prescription" @closeDialog="closeDialogil"></prescriptionPicture>
    <!-- 修改订单 -->
    <addEditOrder ref="orderEdit" :orderId="orderId" :staffTitle="staffTitle" :orderInformation="orderInformation"
      :operationType="operationType" @refreshList="refreshList">
    </addEditOrder>
  </div>
</template>

<script>
  import {
    getWaybill,
    waybillDelivery,
    putUpdateStatus
  } from '@/api/waybill'
  import {
    getCoolerBox,
    getRaftCoolerBox
  } from '@/api/incubator.js'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import forms from '@/components/forms'
  import orderDetails from '@/components/orderDetails'
  import prescriptionPicture from '@/components/prescriptionPicture'
  import addEditOrder from '@/components/addEditOrder'
  import {
    employee,
    sendList
  } from "./delivered.js";
  import {
    getUser
  } from '@/api/user'
  import {
    allocationState
  } from '@/assets/js/blockSort'
  export default {
    name: 'OrderManagement',
    components: {
      actionBar,
      tables,
      pagination,
      forms,
      orderDetails,
      prescriptionPicture,
      addEditOrder
    },
    data() {
      return {
        operateList: [{
          type: 'sends',
          title: '批量分配',
          colour: 'success'
        }],
        formList: [{
          type: 'input',
          label: '订单编号',
          field: 'waybillNo',
          placeholder: '请输入订单编号',
        }, {
          type: 'input',
          label: '配送员姓名',
          field: 'delivery_name',
          placeholder: '请输入配送员姓名',
        }, {
          type: 'input',
          label: '患者名称',
          field: 'Consignee_address_name',
          placeholder: '请输入患者名称',
        }, {
          type: 'input',
          label: '患者手机号',
          field: 'Consignee_address_phone',
          placeholder: '请输入患者手机号',
        }, {
          type: 'select',
          label: '分配状态',
          field: 'status',
          placeholder: '请选择分配状态',
          options: allocationState(),
        }],
        searchRuleForm: {
          waybillNo: '',
          delivery_name: '',
          Consignee_address_name: '',
          Consignee_address_phone: '',
          status: null,
        },
        searchValue: {},
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        Total: 0,
        operationType: '',
        tableData: [],
        tableList: [],
        btnData: [{
          type: 'logs',
          label: '详情',
          icon: 'el-icon-tickets',
          style: 'success',
        }, {
          type: 'edit',
          label: '修改',
          icon: 'el-icon-edit',
          style: 'success',
        }, {
          type: 'send',
          label: '处方',
          icon: 'el-icon-tickets',
          style: 'primary',
        }, {
          type: 'sign',
          label: '分配',
          icon: 'el-icon-share',
          style: 'warning',
        }, {
          type: 'delOrder',
          label: '取消订单',
          icon: 'el-icon-delete',
          style: 'danger',
        }],
        sendDialogVisible: false,
        sendRuleList: sendList(),
        sendRuleForm: {
          fileList: [],
          deliveryId: null,
          coolerBoxId: null,
          code: [],
          tamperProofLabelImg: '',
          tamperProofLabel: '',
        },
        sendConfirmLoading: false,
        page: 1,
        staffName: '',
        limitNo: true,
        sendOrdersId: 2,
        waybillIdList: [],
        orderId: null,
        waybillData: {},
        srcList: [],
        fileList: [],
        staffTitle: '',
        orderInformation: {},
      }
    },
    mounted() {
      let arr = employee()
      arr.forEach(item => {
        if (item.field == 'unpackBtn') {
          item.labelButton = this.btnData
        }
      })
      this.tableList = arr
      this.getList()
    },
    methods: {
      // 搜索
      searchProtocol(value) {
        this.Pagination.PageIndex = 1
        this.searchValue = value
        if (value.time) {
          this.searchValue.orderStartTime = value.time[0]
          this.searchValue.orderEndTime = value.time[1]
        }
        this.getList()
      },
      // 获取运单列表
      getList() {
        var params = {
          status: 3,
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          ...this.searchValue
        }
        delete params.time
        getWaybill(params).then(res => {
          if (res.code == 200) {
            this.tableData = res.data.list
            this.tableData.forEach(item => {
              if (item.iceRaftCode) {
                item.iceRaftCode = item.iceRaftCode.toString()
              }
              item.visible = false
            })
            this.Total = res.data.count
          }
        })
      },
      async openModel(type) {
        // console.log(type, 87)
        this.operationType = type
        if (type == 'sends') {
          const arrID = this.$refs.refWaybill.waybillIds
          let arrList = []
          arrID.forEach(item => {
            arrList.push(item.id)
          })
          this.waybillIdList = arrList
          if (arrList.length != 0) {
            this.sendDialogVisible = true
            var arr = await this.getUserList()
            this.sendRuleList.forEach(item => {
              if (item.field == 'reCheckId') {
                item.options = arr
              }
            })
            this.sendRuleList.forEach(item => {
              if (item.field == 'deliveryId') {
                item.options = arr
              }
            })
            this.getIncubator(2)
          } else {
            this.$message({
              message: '请先选择需要批量操作的订单',
              type: 'warning'
            });
          }
        }
      },
      async buttonData(row, type) {
        this.operationType = type
        this.orderId = row.id
        if (type == 'logs') {
          this.$refs.order.staffDialogVisible = true
          this.$refs.order.tableData = row.drugs
          this.waybillData = row
          this.waybillData.coolerBoxName = row.coolerBox.name
          this.waybillData.courierName = row.delivery.nickName
          this.waybillData.courierPhone = row.delivery.phone
          this.waybillData.reCheckName = row.reCheck.nickName
          this.waybillData.reCheckPhone = row.reCheck.phone
        } else if (type == 'send') {
          if (row.prescription) {
            this.srcList = row.prescription
          }
          this.$refs.picture.prescriptionVisible = true
        } else if (type == 'sign') {
          this.sendDialogVisible = true
          if (row.tamperProofLabelImg) {
            var arr = row.tamperProofLabelImg.split(',')
            var arr3 = []
            arr.forEach((item, index) => {
              var arr1 = {
                url: '',
              }
              arr1.url = item
              arr3.push(arr1)
            })
            this.sendRuleForm.fileList = arr3
            this.sendRuleForm.tamperProofLabelImg = row.tamperProofLabelImg
          }
          // this.sendRuleForm.tamperProofLabelImg = row.tamperProofLabelImg
          this.sendRuleForm.tamperProofLabel = row.tamperProofLabel
          var arr = await this.getUserList()
          this.sendRuleList.forEach(item => {
            if (item.field == 'reCheckId') {
              item.options = arr
            }
          })
          this.sendRuleList.forEach(item => {
            if (item.field == 'deliveryId') {
              item.options = arr
            }
          })
          this.getIncubator(2)
        } else if (type == 'delOrder') {
          this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let arrOrderId = []
            arrOrderId.push(row.id)
            putUpdateStatus({
              id: arrOrderId,
              status: 8,
            }).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
            })
          }).catch(() => {})
        } else if (type == "edit") {
          this.staffTitle = '修改'
          this.orderInformation = {}
          this.$refs.orderEdit.staffDialogVisible = true
          this.$nextTick(() => {
            this.orderInformation = row
          })
        }
      },
      // 添加修改刷新列表
      refreshList() {
        this.getList()
      },
      // 触底事件
      handleScroll() {
        if (this.limitNo) {
          this.getIncubator()
        }
      },
      // 搜索
      remoteMethod(value, type) {
        this.resetSelect(type)
        this.staffName = value
        if (type == 'coolerBoxId') {
          this.getIncubator(this.sendOrdersId)
        } else {
          this.searchAssignment(type)
        }
      },
      // 搜索赋值
      async searchAssignment(type) {
        var arr = await this.getUserList()
        this.sendRuleList.forEach(item => {
          if (item.field == type) {
            item.options = arr
          }
        })
      },
      // 重置选择员工
      resetSelect(type) {
        this.sendRuleList.forEach(item => {
          if (item.field == type) {
            item.options = []
          }
        })
        this.page = 1
        this.limitNo = true
        this.staffName = ''
      },
      // 运单分配
      sendHandleAdd() {
        let flag = this.$refs['sendRules'].validateForm();
        if (flag) {
          this.sendConfirmLoading = true
          let arrID = []
          if (this.operationType == 'sign') {
            arrID.push(this.orderId)
          } else if (this.operationType == 'sends') {
            arrID = this.waybillIdList
          }
          const param = {
            waybillIds: arrID,
            deliveryId: Number(this.sendRuleForm.deliveryId),
            coolerBoxId: Number(this.sendRuleForm.coolerBoxId),
            iceRaftCode: this.sendRuleForm.code,
            tamperProofLabel: this.sendRuleForm.tamperProofLabel,
            tamperProofLabelImg: this.sendRuleForm.tamperProofLabelImg,
          }
          if (param.iceRaftCode) {
            delete param.iceRaftCode
          }
          if (this.sendRuleForm.fileList) {
            var fileImage = this.picture(this.sendRuleForm.fileList)
            param.tamperProofLabelImg = fileImage
          }
          waybillDelivery(param).then(res => {
            if (res.code == 200) {
              this.$message({
                message: res.msg,
                type: 'success'
              });
              this.getList()
              this.sendDialogVisible = false
            } else if (res.code == 2000) {
              let arrTitle = res.data
              let title = ' ,请将冰排' + arrTitle.toString() + '重新入库'
              this.$message({
                showClose: true,
                message: res.msg + title,
                duration: 0,
                type: 'warning'
              });
              this.sendDialogVisible = false
            }
            this.sendConfirmLoading = false
          }).catch(() => {
            this.sendConfirmLoading = false
          })
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      picture(arr) {
        var imgList = JSON.parse(JSON.stringify(arr))
        var imgArr = []
        imgList.forEach((item, index) => {
          imgArr.push(item.url)
        })
        var imgString = imgArr.join()
        return imgString
      },
      // 获取保温箱列表
      getIncubator(type) {
        let arrList = []
        let params = {
          page: this.page,
          pageSize: 10,
          status: '2',
          name: this.staffName,
        }
        getCoolerBox(params).then(res => {
          if (res.code == 200) {
            let arr = res.data.list
            let arrList = []
            arr.forEach(item1 => {
              var arrData = {
                label: null,
                value: null,
              }
              arrData.label = item1.name
              arrData.value = item1.id
              arrList.push(arrData)
            })
            if (this.limitNo == true) {
              this.sendRuleList.forEach(item => {
                if (item.field == 'coolerBoxId') {
                  item.options = item.options.concat(arrList);
                  let some = [];
                  item.options.forEach(el => {
                    if (!some.some(e => e.value == el.value)) {
                      some.push(el)
                    }
                  })
                  item.options = some
                }
              })
            }
            if (arrList.length >= 10) {
              this.page = ++this.page;
            } else {
              // 已经没数据了 不需要增加数据
              this.limitNo = false;
            }
          }
        })
      },
      // 获取不同用户列表
      getUserList() {
        return new Promise((resolve, reject) => {
          var params = {
            page: 1,
            pageSize: 999,
            // type: 3,
            name: this.staffName,
          }
          getUser(params).then(res => {
            if (res.code == 200) {
              let arr = res.data.list
              let arrList = []
              arr.forEach(item1 => {
                var arrData = {
                  label: null,
                  value: null,
                }
                arrData.label = item1.nickName
                arrData.value = item1.id
                arrList.push(arrData)
              })
              resolve(arrList)
            }
          }).catch((err) => {
            reject(err)
          })
        })
      },
      // 获取保温箱搜索选择框数据
      changeOption(id, field) {
        if (field == 'coolerBoxId') {
          getRaftCoolerBox({
            coolerBoxId: id
          }).then(res => {
            if (res.code == 200) {
              if (res.data) {
                this.sendRuleForm.code = res.data
                this.$refs.sendRules.inputsList = res.data
              }
            }
          })
        }
      },
      // 处方更新
      prescription() {
        this.Pagination.PageIndex = 1
        this.getList()
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      // 清空表单
      closeDialog() {
        // this.$refs.sendRules.resetCheck();
      },
      closeDialogil() {
        this.srcList = []
        this.fileList = []
      }
    },
  }
</script>

<style lang="scss" scoped>
</style>
