<template>
  <!-- 未确定订单 -->
  <div>
    <div ref="grabble">
      <actionBar :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm" @openModel="openModel"
        @searchProtocol="searchProtocol"></actionBar>
    </div>
    <div class="card_content">
      <!-- 表单 -->
      <tables ref="refWaybill" controlswidth="450px" 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>
    <!-- 处方 -->
    <prescriptionPicture ref="picture" :srcList="srcList" :fileList="fileList"></prescriptionPicture>
    <!-- 添加订单 -->
    <el-dialog top="5vh" :title="staffTitle" :visible.sync="staffDialogVisible" width="800px"
      :close-on-click-modal="false" @close="closePopup">
      <forms ref="userRules" :formNewList="personnelList" :ruleForm="personnelForm" labelWidth="80px"
        @remoteMethod="remoteSearch">
      </forms>
      <div class="waybill_item">
        <waybillForm ref="recipients" title="患者信息" :conserveFlag="conserveFlag" thinTitle="患者簿"
          :ruleForm="recipientsForm" @addressBook="getAddressBook('recipients')" @conserveSelect="conserveSelectil">
        </waybillForm>
      </div>
      <forms ref="childRules" :formNewList="formRuleList" :ruleForm="ruleForm" labelWidth="80px">
      </forms>
      <el-dialog width="60%" title="地址簿" :visible.sync="innerVisible" append-to-body>
        <div class="space_between_in" style="margin-bottom: 15px;">
          <div style="display: flex;align-items: center;width: 100%;">
            <h3 style="margin-left: 10px;flex: none;">搜索：</h3>
            <el-input v-model="bookInput" style="width: 100%;" placeholder="请输入姓名、电话、地址快速查找"
              @input="fastSearch()"></el-input>
          </div>
        </div>
        <div class="card_book_list">
          <!-- 表单 -->
          <tables :suspension="true" :tableList="bookTableList" :tableData="bookTableData" @cellClick="cellClick"
            @buttonData="buttonData">
          </tables>
          <!-- 分页 -->
          <div v-if="bookTotal">
            <pagination :total="bookTotal" :currentPage="bookPagination.PageIndex" @changeSize="bookChangeSize"
              @changeCurrent="bookChangeCurrent">
            </pagination>
          </div>
        </div>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="staffDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="转门店" :visible.sync="signDialogVisible" width="500px" :close-on-click-modal="false"
      @close="closeDialog1">
      <forms ref="signRules" :formNewList="signRuleList" :ruleForm="signRuleForm" labelWidth="80px"
        @remoteMethod="remoteSearch">
      </forms>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="signDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="signConfirmLoading" @click="signHandleAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getWaybill,
    addWaybill,
    putWaybill,
    putUpdateStatus,
    putturnarounds
  } from '@/api/waybill'
  import {
    getAddress
  } from '@/api/address'
  import {
    getUser
  } from '@/api/user'
  import {
    getCompanyDept
  } from '@/api/company'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import orderDetails from '@/components/orderDetails'
  import prescriptionPicture from '@/components/prescriptionPicture'
  import waybillForm from '@/components/waybillForm'
  import forms from '@/components/forms'
  import {
    employee,
    formRules,
    consignmentList,
    addressBook,
    signList,
  } from "./uncertain.js";
  import {
    WaybillStatus
  } from '@/assets/js/blockSort'
  export default {
    name: 'OrderManagement',
    components: {
      actionBar,
      tables,
      pagination,
      orderDetails,
      prescriptionPicture,
      waybillForm,
      forms,
    },
    data() {
      return {
        operateList: [{
          type: 'sends',
          title: '批量确定',
          icon: 'el-icon-thumb',
          colour: 'success'
        }, {
          type: 'add',
          title: '添加订单',
          icon: 'el-icon-plus',
        }],
        formList: [{
          type: 'input',
          label: '订单编号',
          field: 'waybillNo',
          placeholder: '请输入订单编号',
        }, {
          type: 'input',
          label: '门店名称',
          field: 'orderNo',
          placeholder: '请输入门店名称',
        }, {
          type: 'input',
          label: '配送员姓名',
          field: 'orderNo',
          placeholder: '请输入配送员姓名',
        }, {
          type: 'input',
          label: '患者名称',
          field: 'orderNo',
          placeholder: '请输入患者名称',
        }, {
          type: 'input',
          label: '患者手机号',
          field: 'orderNo',
          placeholder: '请输入患者手机号',
        }],
        searchRuleForm: {
          orderNo: '',
          status: null,
          time: [],
        },
        searchValue: {},
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        Total: 0,
        operationType: '',
        tableData: [],
        tableList: [],
        btnData: [{
          type: 'confirm',
          label: '确定',
          icon: 'el-icon-thumb',
          style: 'success',
        }, {
          type: 'logs',
          label: '详情',
          icon: 'el-icon-tickets',
          style: 'success',
        }, {
          type: 'send',
          label: '处方',
          icon: 'el-icon-tickets',
          style: 'primary',
        }, {
          type: 'edit',
          label: '修改',
          icon: 'el-icon-edit',
          style: 'success',
        }, {
          type: 'sign',
          label: '转门店',
          icon: 'el-icon-share',
          style: 'warning',
        }, {
          type: 'delOrder',
          label: '取消订单',
          icon: 'el-icon-delete',
          style: 'danger',
        }],
        waybillData: {},
        srcList: [],
        fileList: [{
          name: 'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        }, {
          name: 'food2.jpeg',
          url: 'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg'
        }],
        staffTitle: '添加',
        staffDialogVisible: false,
        recipientsForm: {
          name: '',
          phone: '',
          region: '',
          address: '',
        },
        personnelList: consignmentList(),
        personnelForm: {
          orderNo: null,
          reCheckId: null,
          deliveryId: null,
        },
        delivererName: '',
        ruleForm: {
          tamperProofLabel: '',
          tamperProofLabelImg: '',
          remark: '',
          fileList: [],
        },
        formRuleList: [],
        conserveFlag: true,
        saveConsigneeAddress: true,
        innerVisible: false,
        bookInput: '',
        bookTableList: [],
        bookTableData: [],
        bookType: '',
        bookPagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        bookTotal: 0,
        confirmLoading: false,
        orderId: null,

        signDialogVisible: false,
        signRuleList: signList(),
        signRuleForm: {
          deptId: '',
          // rejectionReason: '',
        },
        signConfirmLoading: false,
      }
    },
    mounted() {
      const dataList = formRules();
      this.formRuleList = dataList;
      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: 1,
          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
          }
        })
      },
      // 获取地址簿
      getAddressBook(type) {
        this.bookTableList = addressBook()
        this.bookType = type
        this.innerVisible = true
        this.getSenderSend()
      },
      // 快速搜索
      fastSearch() {
        this.bookPagination.PageIndex = 1
        if (this.bookType == 'deliverer') {
          this.getDelivererList()
        }
      },
      // 获取寄/收列表
      getSenderSend() {
        let address = ''
        if (this.bookType == 'recipients') {
          address = 'consignee'
        } else {
          address = this.bookType
        }
        getAddress({
          page: this.bookPagination.PageIndex,
          pageSize: this.bookPagination.PageSize,
          name: this.bookInput,
          addressType: address,
        }).then(res => {
          if (res.code == 200) {
            this.bookTableData = res.data.list
            this.bookTotal = res.data.count
          }
        })
      },
      openModel(type) {
        this.operationType = type
        if (type == 'add') {
          this.conserveFlag = true
          this.staffTitle = '添加订单'
          this.staffDialogVisible = true
          this.$nextTick(() => {
            // this.$refs.sender.radio = '1'
            this.$refs.recipients.radio = '1'
            this.getReviewerList()
            this.getDelivererList()
          })
        } else if (type == 'sends') {
          const arrID = this.$refs.refWaybill.waybillIds
          let arrList = []
          arrID.forEach(item => {
            arrList.push(item.id)
          })
          if (arrList.length != 0) {
            this.modifyOrderStatus(arrList)
          } else {
            this.$message({
              message: '请先选择需要批量操作的运单',
              type: 'warning'
            });
          }
        }
      },
      // 弹窗表单添加
      async handleAdd() {
        let senderFlag = this.$refs['userRules'].validateForm();
        let recipientsFlag = this.$refs['recipients'].validateForm();
        let childRulesFlag = this.$refs['childRules'].validateForm();
        if (senderFlag && recipientsFlag && childRulesFlag) {
          this.confirmLoading = true
          var params = {
            consigneeAddressName: this.recipientsForm.name,
            consigneeAddressPhone: this.recipientsForm.phone,
            consigneeAddressDetails: this.recipientsForm.address,
            saveConsigneeAddress: this.saveConsigneeAddress,
            orderNo: this.personnelForm.orderNo,
            deliveryId: Number(this.personnelForm.deliveryId),
            reCheckId: Number(this.personnelForm.reCheckId),
            ...this.ruleForm
          }
          if (this.ruleForm.fileList) {
            var fileImage = this.picture(this.ruleForm.fileList)
            params.tamperProofLabelImg = fileImage
          }
          if (this.operationType == 'add') {
            delete params.fileList
            await addWaybill(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.staffDialogVisible = false
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
          } else if (this.operationType == 'edit') {
            delete params.fileList
            params.id = this.orderId
            await putWaybill(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.staffDialogVisible = false
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = 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
      },
      // 选择table其中某一项
      cellClick(row) {
        this.innerVisible = false
        const param = {
          ...row
        }
        if (this.bookType == 'recipients') {
          this.recipientsForm = param
          this.$nextTick(() => {
            this.$refs.recipients.radio = ''
            // this.$refs['recipients'].clickitem('1')
            this.$refs['recipients'].validateForm();
          })
        } else if (this.bookType == 'deliverer') {
          this.delivererForm.name = param.nickName
          this.delivererForm.phone = param.phone
          this.$nextTick(() => {
            this.$refs['deliverer'].validateForm();
          })
        }
      },
      buttonData(row, type) {
        this.operationType = type
        this.orderId = row.id
        if (type == 'logs') {
          this.$refs.order.staffDialogVisible = true
          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') {
          const urls = this.fileList.map(obj => obj.url)
          this.srcList = urls
          this.$refs.picture.prescriptionVisible = true
        } else if (type == 'confirm') {
          let arrOrderId = []
          arrOrderId.push(row.id)
          this.modifyOrderStatus(arrOrderId, 2)
        } else if (type == 'edit') {
          // this.getReviewerList()
          // this.getDelivererList()
          this.conserveFlag = false
          this.staffTitle = '编辑'
          this.staffDialogVisible = true
          setTimeout(() => {
            this.$nextTick(() => {
              this.recipientsForm.name = row.consigneeAddressName
              this.recipientsForm.phone = row.consigneeAddressPhone
              this.recipientsForm.address = row.consigneeAddressDetails
              this.ruleForm.tamperProofLabel = row.tamperProofLabel
              this.personnelForm.orderNo = row.orderNo
              this.personnelForm.reCheckId = String(row.reCheckId)
              this.personnelForm.deliveryId = String(row.deliveryId)
              if (row.tamperProofLabelImg) {
                var arr = row.tamperProofLabelImg.split(',')
                var arr3 = []
                arr.forEach((item, index) => {
                  var arr1 = {
                    url: '',
                  }
                  arr1.url = item
                  arr3.push(arr1)
                })
                this.ruleForm.fileList = arr3
                this.ruleForm.tamperProofLabelImg = row.tamperProofLabelImg
              }
              this.ruleForm.remark = row.remark
            })
          })
        } else if (type == 'sign') {
          this.signDialogVisible = true
          this.waybillNo = row.waybillNo
          this.getAcquireStore()
        } 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(() => {})
        }
      },
      // 修改订单状态
      modifyOrderStatus(arrID, type) {
        putUpdateStatus({
          id: arrID,
          status: type,
        }).then(res => {
          if (res.code == 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.getList()
          }
        })
      },
      // 转门店
      signHandleAdd() {
        let flag = this.$refs['signRules'].validateForm();
        if (flag) {
          this.signConfirmLoading = true
          let params = {
            waybillNo: this.waybillNo,
            deptId: Number(this.signRuleForm.deptId),
          }
          putturnarounds(params).then(res => {
            if (res.code == 200) {
              this.signDialogVisible = false
              this.getList()
            }
            this.signConfirmLoading = false
          }).catch(() => {
            this.signConfirmLoading = false
          })
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      remoteSearch(value, type) {
        this.delivererName = value
        if (type == 'deliveryId') {
          this.personnelList.forEach(item => {
            if (item.field == 'deliveryId') {
              item.options = []
            }
          })
          this.getDelivererList()
        } else if (type == 'reCheckId') {
          this.personnelList.forEach(item => {
            if (item.field == 'reCheckId') {
              item.options = []
            }
          })
          this.getReviewerList()
        } else if (type == 'deptId') {
          this.signRuleList.forEach(item => {
            if (item.field == 'deptId') {
              item.options = []
            }
          })
          this.getAcquireStore()
        }
      },
      // 复核人
      getReviewerList() {
        var params = {
          page: 1,
          pageSize: 999,
          name: this.delivererName,
        }
        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)
            })
            this.personnelList.forEach(item => {
              if (item.field == 'reCheckId') {
                item.options = item.options.concat(arrList)
              }
            })
          }
        })
      },
      getDelivererList() {
        var params = {
          page: 1,
          pageSize: 999,
          // type: 3,
          name: this.delivererName,
        }
        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)
            })
            this.personnelList.forEach(item => {
              if (item.field == 'deliveryId') {
                item.options = item.options.concat(arrList)
              }
            })
          }
        })
      },
      // 获取门店
      getAcquireStore() {
        var params = {
          page: 1,
          pageSize: 999,
          // type: 3,
          name: this.delivererName,
        }
        getCompanyDept(params).then(res => {
          // signRuleList
          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)
            })
            this.signRuleList.forEach(item => {
              if (item.field == 'deptId') {
                item.options = item.options.concat(arrList)
              }
            })
          }
        })
      },
      // 地址簿
      bookChangeSize(val) {
        this.bookPagination.PageSize = val
        if (this.bookType == 'deliverer') {
          this.getDelivererList()
        } else {
          this.getSenderSend()
        }
      },
      bookChangeCurrent(val) {
        this.bookPagination.PageIndex = val
        if (this.bookType == 'deliverer') {
          this.getDelivererList()
        } else {
          this.getSenderSend()
        }
      },
      conserveSelectil(type) {
        if (type) {
          this.saveConsigneeAddress = true
        } else {
          this.saveConsigneeAddress = false
        }
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      // 清空表单
      closeDialog1() {
        this.$refs.signRules.resetCheck();
      },
      // 关闭清空表单
      closePopup() {
        this.ruleForm.fileList = []
        // this.$refs.sender.resetForm()
        this.$refs.recipients.resetForm()
        // this.$refs.deliverer.resetForm()
        this.$refs.childRules.resetCheck()
        this.$refs.userRules.resetCheck()
        this.personnelList.forEach(item => {
          item.options = []
        })
      }
    },
  }
</script>

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