<template>
  <!-- 运单管理 -->
  <div class="waybill_home">
    <actionBar :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm" @openModel="openModel"
      @searchProtocol="searchProtocol"></actionBar>
    <div class="card_content">
      <!-- 表单 -->
      <tables ref="refWaybill" :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>
    <el-dialog :title="staffTitle" :visible.sync="staffDialogVisible" width="60%" :close-on-click-modal="false"
      @close="closePopup">
      <div class="card_waybill">
        <div class="waybill_item" style="margin-right: 10px;">
          <waybillForm ref="sender" title="寄件人" :ruleForm="senderForm" @addressBook="getAddressBook('sender')">
          </waybillForm>
        </div>
        <div class="waybill_item" style="margin-left: 10px;">
          <waybillForm ref="recipients" title="收件人" :ruleForm="recipientsForm"
            @addressBook="getAddressBook('consignee')"></waybillForm>
        </div>
      </div>
      <div style="margin-top: 20px;">
        <forms ref="childRules" :formNewList="formRuleList" :ruleForm="ruleForm" labelWidth="80px">
        </forms>
      </div>
      <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="sendDialogVisible" width="500px" :close-on-click-modal="false"
      @close="closeDialog">
      <forms ref="sendRules" :formNewList="sendRuleList" :ruleForm="sendRuleForm" labelWidth="80px"
        @handleScroll="handleScroll" @remoteMethod="remoteMethod">
      </forms>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="sendDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="sendConfirmLoading" @click="sendHandleAdd">确 定</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">
      </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>
    <orderDetails ref="order" :waybillData="waybillData"></orderDetails>
    <el-dialog title="批量导入" :visible.sync="bulkImportVisible" width="600px" @close="closeDialog2">
      <div class="card_customer">
        <span>下单客户</span>
        <el-input v-model="orderCustomer" placeholder="请输入内容"></el-input>
      </div>
      <div class="card_bulkImport">
        <el-upload ref="mYupload" class="upload-demo" accept=".xls,.xlsx" drag action="#" :limit="1" multiple
          :http-request="UploadImage">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">请上传xls或者xlsx格式文件</div>
        </el-upload>
        <div style="margin-top: 15px;">
          <el-button size="medium" type="primary" icon="el-icon-upload" :loading="importFlag"
            @click="immediateImport">立即导入</el-button>
          <el-button size="medium" icon="el-icon-download" :loading="downloadFlag"
            @click="templateDownload">模板下载</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getWaybill,
    addWaybill,
    putWaybill,
    delWaybill,
    waybillDelivery,
    waybillImport,
    exportTemplate,
    getReceipt
  } from '@/api/waybill'
  import {
    addAddress,
  } from '@/api/address'
  import {
    getCoolerBox
  } from '@/api/incubator.js'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import waybillForm from '@/components/waybillForm'
  import forms from '@/components/forms'
  import orderDetails from '@/components/orderDetails'
  import {
    formRules,
    employee,
    addressBook,
    sendList,
    signList
  } from "./waybill.js";
  import {
    WaybillStatus
  } from '@/assets/js/blockSort'
  import {
    regionData,
    CodeToText
  } from 'element-china-area-data'
  export default {
    name: 'WaybillManagement',
    components: {
      actionBar,
      tables,
      pagination,
      waybillForm,
      forms,
      orderDetails
    },
    data() {
      return {
        operateList: [{
          type: 'sends',
          title: '批量派单',
          colour: 'success'
        }, {
          type: 'import',
          title: '批量导入',
          colour: 'warning'
        }, {
          type: 'add',
          title: '添加运单',
          icon: 'el-icon-plus',
        }],
        formList: [{
          type: 'input',
          label: '运单号',
          field: 'waybillNo',
          placeholder: '请输入运单号',
        }, {
          type: 'select',
          label: '状态',
          field: 'status',
          placeholder: '请选择状态',
          options: WaybillStatus(),
        }, {
          type: 'picker',
          label: '下单时间',
          field: 'time',
          placeholder: '下单时间',
        }],
        searchRuleForm: {
          waybillNo: '',
          status: null,
          time: [],
        },
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        Total: 0,
        tableData: [],
        operationType: '',
        tableList: employee(),
        confirmLoading: false,
        staffTitle: '添加',
        staffDialogVisible: false,
        senderForm: {
          name: '',
          phone: '',
          region: '',
          address: '',
        },
        recipientsForm: {
          name: '',
          phone: '',
          region: '',
          address: '',
        },
        bookList: {
          field: 'action',
          label: '操作',
          align: 'center',
          labelButton: [{
            type: 'edit',
            label: '编辑',
            icon: 'el-icon-edit',
            style: 'primary',
          }, {
            type: 'del',
            label: '删除',
            icon: 'el-icon-delete',
            style: 'danger',
          }]
        },
        ruleForm: {
          TamperProofLabel: '',
          remark: '',
        },
        formRuleList: [],
        bookType: '',
        sendDialogVisible: false,
        sendRuleList: sendList(),
        sendRuleForm: {
          coolerBoxId: null,
        },
        sendConfirmLoading: false,
        orderId: null,
        waybillIdList: [],
        waybillData: {},
        bulkImportVisible: false,
        importFlag: false,
        downloadFlag: false,
        importFile: null,
        orderCustomer: '',
        page: 1,
        staffName: '',
        limitNo: true,
        sendOrdersId: 2,
        searchValue: {},
        signDialogVisible: false,
        signRuleList: signList(),
        signRuleForm: {
          status: '',
          rejectionReason: '',
        },
        signConfirmLoading: false,
        waybillNo: '',
      }
    },
    mounted() {
      const dataList = formRules();
      this.formRuleList = dataList;
      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 = {
          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.Total = res.data.count
          }
        })
      },
      // 弹窗表单添加
      async handleAdd() {
        let senderFlag = this.$refs['sender'].validateForm();
        let recipientsFlag = this.$refs['recipients'].validateForm();
        let flag = this.$refs['childRules'].validateForm();
        if (senderFlag && recipientsFlag && flag) {
          this.confirmLoading = true
          var params = {
            senderAddressName: this.senderForm.name,
            senderAddressPhone: this.senderForm.phone,
            senderAddressDetails: this.senderForm.address,
            consigneeAddressName: this.recipientsForm.name,
            consigneeAddressPhone: this.recipientsForm.phone,
            consigneeAddressDetails: this.recipientsForm.address,
            ...this.ruleForm
          }
          if (this.operationType == 'add') {
            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') {
            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('表单信息不完整，请继续填写完整');
        }
        // console.log(this.ruleForm,86)
        // console.log(this.senderForm, this.recipientsForm, 665)
      },
      // 添加寄件人
      getSender(value) {
        return new Promise((resolve, reject) => {
          var params = {
            addressType: 'sender',
            ...value
          }
          params.provinceId = value.regionCode[0]
          params.cityId = value.regionCode[1]
          params.regionId = value.regionCode[2]
          const regionArr = value.region.split('/')
          params.provinceName = regionArr[0]
          params.cityName = regionArr[1]
          params.regionName = regionArr[2]
          delete params.regionCode
          delete params.region
          addAddress(params).then(res => {
            if (res.code == 200) {
              const orderID = res.data
              resolve(orderID);
            }
          }).catch((error) => {
            reject(error)
          })
        });
      },
      // 添加收件人
      getRecipients(value) {
        return new Promise((resolve, reject) => {
          var params = {
            addressType: 'consignee',
            ...value
          }
          params.provinceId = value.regionCode[0]
          params.cityId = value.regionCode[1]
          params.regionId = value.regionCode[2]
          const regionArr = value.region.split('/')
          params.provinceName = regionArr[0]
          params.cityName = regionArr[1]
          params.regionName = regionArr[2]
          delete params.regionCode
          delete params.region
          addAddress(params).then(res => {
            if (res.code == 200) {
              const orderID = res.data
              resolve(orderID);
            }
          }).catch((error) => {
            reject(error)
          })
        });
      },
      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
        } else if (type == 'edit') {
          this.staffTitle = '编辑'
          this.staffDialogVisible = true
          setTimeout(() => {
            this.$nextTick(() => {
              this.senderForm.name = row.senderAddressName
              this.senderForm.phone = row.senderAddressPhone
              this.senderForm.address = row.senderAddressDetails
              this.recipientsForm.name = row.consigneeAddressName
              this.recipientsForm.phone = row.consigneeAddressPhone
              this.recipientsForm.address = row.consigneeAddressDetails
              this.ruleForm.TamperProofLabel = row.tamperProofLabel
              this.ruleForm.remark = row.remark
            })
          })
        } else if (type == 'send') {
          this.sendDialogVisible = true
          this.getUserList(2)
        } else if (type == 'del') {
          this.deleteUser(row.id)
        } else if (type == 'sign') {
          this.signDialogVisible = true
          this.waybillNo = row.waybillNo
          this.signRuleForm.status = row.status
        }
      },
      // 订单派单
      sendHandleAdd() {
        let flag = this.$refs['sendRules'].validateForm();
        if (flag) {
          this.sendConfirmLoading = true
          let arrID = []
          if (this.operationType == 'send') {
            arrID.push(this.orderId)
          } else if (this.operationType == 'sends') {
            arrID = this.waybillIdList
          }
          const param = {
            waybillIds: arrID,
            coolerBoxId: Number(this.sendRuleForm.coolerBoxId),
          }
          waybillDelivery(param).then(res => {
            if (res.code == 200) {
              this.$message({
                message: res.msg,
                type: 'success'
              });
              this.getList()
            }
            this.sendDialogVisible = false
            this.sendConfirmLoading = false
          }).catch(() => {
            this.sendConfirmLoading = false
          })
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      // 签收
      signHandleAdd() {
        let flag = this.$refs['signRules'].validateForm();
        if (flag) {
          this.signConfirmLoading = true
          let params = {
            waybillNo: this.waybillNo,
            ...this.signRuleForm,
          }
          getReceipt(params).then(res => {
            if (res.code == 200) {
              this.$message({
                message: res.msg,
                type: 'success'
              });
              this.signDialogVisible = false
            }
            this.signConfirmLoading = false
          })
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      // 删除用户
      deleteUser(id) {
        this.$confirm('此操作将永久该运单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delWaybill({
            id: id,
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.getList()
            }
          })
        }).catch(() => {});
      },
      // 重置选择员工
      resetSelect() {
        this.sendRuleList.forEach(item => {
          if (item.type == 'searchSelect') {
            item.options = []
          }
        })
        this.page = 1
        this.limitNo = true
        this.staffName = ''
      },
      // 触底事件
      handleScroll() {
        if (this.limitNo) {
          this.getUserList()
        }
      },
      // 搜索
      remoteMethod(value) {
        this.resetSelect()
        this.staffName = value
        this.getUserList(this.sendOrdersId)
      },
      // 获取保温箱列表
      getUserList(type) {
        let arrList = []
        let params = {
          page: this.page,
          pageSize: 10,
          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.type == 'searchSelect') {
                  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;
            }
          }
        })
      },
      // 选项赋值
      optionMatching(value, field) {
        this.sendRuleList.forEach((item, index) => {
          if (item.field == field) {
            item.options = value
          }
        })
      },
      openModel(type) {
        this.operationType = type
        if (type == 'add') {
          this.staffTitle = '添加运单'
          this.staffDialogVisible = true
        } else if (type == 'sends') {
          const arrID = this.$refs.refWaybill.waybillIds
          if (arrID.length != 0) {
            let arr2 = []
            arrID.forEach(item => {
              if (item.status == 1 || item.status == 2) {
                arr2.push(item.id)
              }
            })
            this.waybillIdList = arr2
            if (arr2.length > 0) {
              this.sendDialogVisible = true
              this.getUserList(2)
            } else {
              this.$message({
                message: '请选择未派单的运单',
                type: 'warning'
              });
            }
          } else {
            this.$message({
              message: '请先选择需要批量操作的运单',
              type: 'warning'
            });
          }
          // console.log(type, arrID, '批量派单')
        } else if (type == 'import') {
          this.bulkImportVisible = true
        } else if (type == 'print') {
          const arrID = this.$refs.refWaybill.waybillIds
          if (arrID.length != 0) {
            let arr3 = []
            let arr4 = []
            arrID.forEach(item => {
              if (item.status == 8) {
                arr3.push(item)
                arr4.push(item.id)
              }
            })
            if (arr3.length > 0) {} else {
              this.$message({
                message: '请选择已签收的运单',
                type: 'warning'
              });
            }
          } else {
            this.$message({
              message: '请先选择需要批量操作的运单',
              type: 'warning'
            });
          }
        }
      },
      // 导入
      immediateImport() {
        if (this.importFile) {
          this.importFlag = true
          let formData = new FormData();
          formData.append('file', this.importFile);
          formData.append('customerName', this.orderCustomer);
          waybillImport(formData).then(res => {
            if (res.code == 200) {
              this.bulkImportVisible = false
              this.importFlag = false
              this.getList()
              this.$message({
                message: '恭喜你，导入成功',
                type: 'success'
              });
            }
          })
        } else {
          this.$message({
            message: '请先选择上传文件',
            type: 'warning'
          });
        }
      },
      // 导出模板
      templateDownload() {
        this.downloadFlag = true
        exportTemplate().then(response => {
          if (response.fileName) {
            this.blobDownload(response.data, response.fileName)
          }
          this.downloadFlag = false
        })
      },
      // 上传文件
      UploadImage(param) {
        this.importFile = param.file
      },
      // 导出文件流
      blobDownload(data, name) {
        let m = this;
        var content = data;
        var data = new Blob([content], {
          type: "application/vnd.ms-excel;charset=utf-8"
        });
        var downloadUrl = window.URL.createObjectURL(data);
        var anchor = document.createElement("a");
        anchor.href = downloadUrl;
        anchor.download = decodeURIComponent(name);
        anchor.click();
        window.URL.revokeObjectURL(data);
      },
      getCodeToText(codeArray) {
        let area = "";
        switch (codeArray.length) {
          case 1:
            area += CodeToText[codeArray[0]];
            break;
          case 2:
            area += CodeToText[codeArray[0]] + "/" + CodeToText[codeArray[1]];
            break;
          case 3:
            area +=
              CodeToText[codeArray[0]] +
              "/" +
              CodeToText[codeArray[1]] +
              "/" +
              CodeToText[codeArray[2]];
            break;
          default:
            break;
        }
        return area
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      // 清空表单
      closeDialog() {
        this.$refs.sendRules.resetCheck();
      },
      // 清空表单
      closeDialog1() {
        this.$refs.signRules.resetCheck();
      },
      // 清空表单
      closeDialog2() {
        this.$refs.mYupload.clearFiles();
      },
      // 关闭清空表单
      closePopup() {
        this.$refs.sender.resetForm()
        this.$refs.recipients.resetForm()
        this.$refs.childRules.resetCheck()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .waybill_home ::v-deep .el-dialog__body {
    padding: 0px 20px 30px 20px;
  }

  .waybil_form ::v-deep .el-cascader {
    width: 100% !important;
  }

  .card_waybill {
    display: flex;
    border-bottom: 1px solid #E4E7ED;
  }

  .waybill_item {
    width: 50%;
  }

  .card_book_list {
    border: 1px solid #DCDFE6;
  }

  .card_bulkImport {
    width: 100%;
  }

  ::v-deep .el-upload {
    width: 100%;
  }

  ::v-deep .el-upload-dragger {
    width: 100%;
  }

  .card_customer {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    span {
      flex: none;
      font-size: 15px;
      margin-right: 8px;
    }
  }
</style>
