<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>
      <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;">
            <h3 style="margin-left: 10px;flex: none;">搜索：</h3>
            <el-input v-model="bookInput" style="width: 260px;" placeholder="请输入姓名、电话、地址快速查找"></el-input>
          </div>
          <el-radio-group v-model="tabPosition" @input="handleClick">
            <el-radio-button label="my">我的</el-radio-button>
            <el-radio-button label="all">全部</el-radio-button>
          </el-radio-group>
        </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="sendDialogVisible" width="500px" :close-on-click-modal="false"
      @close="closeDialog">
      <forms ref="sendRules" :formNewList="sendRuleList" :ruleForm="sendRuleForm" labelWidth="80px"
        @radioInput="radioInput" @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>
    <orderDetails ref="order" :waybillData="waybillData"></orderDetails>
    <el-dialog title="批量导入" :visible.sync="bulkImportVisible" width="600px">
      <div class="card_customer">
        <span>下单客户</span>
        <el-input v-model="orderCustomer" placeholder="请输入内容"></el-input>
      </div>
      <div class="card_bulkImport">
        <el-upload class="upload-demo" 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,
    getWaybillDetails,
    addWaybill,
    putWaybill,
    delWaybill,
    waybillDelivery,
    waybillImport,
    exportTemplate,
    getTemperature
  } from '@/api/waybill'
  import {
    getAddress,
    getAddressDetails,
    addAddress,
    putAddress,
    delAddress
  } from '@/api/address'
  import {
    getWarehouse
  } from '@/api/warehouse.js'
  import {
    getCar
  } from '@/api/vehicle.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
  } 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: 'add',
          title: '添加运单',
          icon: 'el-icon-plus',
        }, {
          type: 'sends',
          title: '批量派单',
          colour: 'success'
        }, {
          type: 'import',
          title: '批量导入',
          colour: 'warning'
        }],
        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(),
        bookTableData: [],
        bookPagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        bookTotal: 0,
        confirmLoading: false,
        staffTitle: '添加',
        staffDialogVisible: false,
        innerVisible: false,
        senderForm: {
          name: '',
          phone: '',
          region: '',
          address: '',
        },
        recipientsForm: {
          name: '',
          phone: '',
          region: '',
          address: '',
        },
        tabPosition: 'my',
        bookInput: '',
        bookTableList: [],
        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: {
          temperatureInterval: '',
          deliveryCondition: '',
          cargoType: '',
          customerName: '',
          remark: '',
        },
        formRuleList: [],
        bookType: '',
        sendDialogVisible: false,
        sendRuleList: sendList(),
        sendRuleForm: {
          type: 2,
          printUserId: null,
        },
        sendConfirmLoading: false,
        orderId: null,
        waybillIdList: [],
        waybillData: {},
        bulkImportVisible: false,
        importFlag: false,
        downloadFlag: false,
        importFile: null,
        orderCustomer: '',
        staffName: '',
        sendOrdersId: 2,
        searchValue: {},
      }
    },
    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
          }
        })
      },
      // 获取地址簿
      getAddressBook(type) {
        this.bookType = type
        this.innerVisible = true
        getAddress({
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          name: this.bookInput,
          addressType: this.bookType,
          dataType: this.tabPosition,
        }).then(res => {
          if (res.code == 200) {
            this.bookTableData = res.data.list
            this.bookTotal = 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
          // let senderAddressId = null
          // let consigneeAddressId = null
          // if (!this.senderForm.id) {
          //   senderAddressId = await this.getSender(this.senderForm)
          // } else {
          //   senderAddressId = this.senderForm.id
          // }
          // if (!this.recipientsForm.id) {
          //   consigneeAddressId = await this.getRecipients(this.recipientsForm)
          // } else {
          //   consigneeAddressId = this.recipientsForm.id
          // }
          var params = {
            // senderAddressId: senderAddressId,
            // consigneeAddressId: consigneeAddressId,
            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)
          })
        });
      },
      // 选择table其中某一项
      cellClick(row) {
        this.innerVisible = false
        const param = {
          ...row
        }
        const arrAddress = []
        if (param.provinceId) {
          arrAddress.push(param.provinceId)
        }
        if (param.provinceId) {
          arrAddress.push(param.cityId)
        }
        if (param.provinceId) {
          arrAddress.push(param.regionId)
        }
        param.regionCode = arrAddress
        param.region = this.getCodeToText(param.regionCode)
        delete param.createBy
        delete param.createdAt
        delete param.deptId
        delete param.isDefault
        delete param.updateBy
        delete param.updatedAt
        if (this.bookType == 'sender') {
          this.senderForm = param
          this.$nextTick(() => {
            this.$refs['sender'].validateForm();
          })
        } else {
          this.recipientsForm = param
          this.$nextTick(() => {
            this.$refs['recipients'].validateForm();
          })
        }
      },
      buttonData(row, type) {
        this.operationType = type
        this.orderId = row.id
        if (type == 'logs') {
          this.$refs.order.staffDialogVisible = true
          this.waybillData = row
          this.waybillData.nickName = row.printUser.nickName
        } 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.temperatureInterval = String(row.temperatureInterval)
              this.ruleForm.deliveryCondition = row.deliveryCondition
              this.ruleForm.cargoType = row.cargoType
              this.ruleForm.customerName = row.customerName
              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 == 'pdf') {
          this.downloadPdf(row)
        }
      },
      // 下载pdf
      downloadPdf(value) {
        getTemperature({
          waybillNo: value.waybillNo,
        }).then(res => {
          // console.log(res,26)
        })
      },
      // 订单派单
      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,
            type: Number(this.sendRuleForm.type),
            printUserId: Number(this.sendRuleForm.printUserId),
          }
          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('表单信息不完整，请继续填写完整');
        }
      },
      // 删除用户
      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(() => {});
      },
      // 单选选择
      radioInput(type) {
        this.sendOrdersId = type
        this.resetSelect()
        this.getUserList(type)
      },
      // 重置选择员工
      resetSelect() {
        this.sendRuleList.forEach(item => {
          if (item.type == 'searchSelect') {
            item.options = []
          }
        })
        this.staffName = ''
        this.sendRuleForm.printUserId = null
      },
      // 搜索
      remoteMethod(value) {
        this.resetSelect()
        this.staffName = value
        this.getUserList(this.sendOrdersId)
      },
      // 获取用户列表
      getUserList(type) {
        let params = {
          page: 1,
          pageSize: 100,
          name: this.staffName,
          isBind: true,
        }
        let arrList = []
        if (type == 2) {
          getWarehouse(params).then(res => {
            if (res.code == 200) {
              const arr = res.data.list
              arr.forEach((item, index) => {
                const commodity = {
                  label: '【' + item.name + '】' + item.user.nickName,
                  value: item.user.id,
                }
                arrList.push(commodity)
              })
            }
          })
        } else if (type == 3) {
          getCar(params).then(res => {
            if (res.code == 200) {
              const arr = res.data.list
              arr.forEach((item, index) => {
                const commodity = {
                  label: '【' + item.carNo + '】' + item.user.nickName,
                  value: item.user.id,
                }
                arrList.push(commodity)
              })
            }
          })
        }
        this.optionMatching(arrList, 'printUserId')
      },
      // 选项赋值
      optionMatching(value, field) {
        this.sendRuleList.forEach((item, index) => {
          if (item.field == field) {
            item.options = value
          }
        })
      },
      openModel(type) {
        this.operationType = type
        if (type == 'add') {
          this.tableBook()
          this.staffTitle = '添加运单'
          this.staffDialogVisible = true
        } else if (type == 'sends') {
          const arrID = this.$refs.refWaybill.waybillIds
          if (arrID.length != 0) {
            this.waybillIdList = arrID
            this.sendDialogVisible = true
            this.getUserList(2)
          } else {
            this.$message({
              message: '请先选择需要批量操作的运单',
              type: 'warning'
            });
          }
          // console.log(type, arrID, '批量派单')
        } else if (type == 'import') {
          this.bulkImportVisible = true
        }
      },
      // 导入
      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 => {
          let filename = '运单模板'
          this.blobDownload(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 = name + ".xls";
        anchor.click();
        window.URL.revokeObjectURL(data);
      },
      // tab选择
      handleClick(tab) {
        this.tableBook()
        this.getAddressBook(this.bookType)
      },
      // tab不同table列表
      tableBook() {
        this.bookTableList = []
        const arr = addressBook()
        if (this.tabPosition == 'my') {
          this.bookTableList = arr
          this.bookTableList.push(this.bookList)
        } else {
          this.bookTableList = arr
        }
      },
      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()
      },
      bookChangeSize(val) {
        this.bookPagination.PageSize = val
        this.getList()
      },
      bookChangeCurrent(val) {
        this.bookPagination.PageIndex = val
        this.getList()
      },
      // 清空表单
      closeDialog() {
        this.$refs.sendRules.resetCheck();
      },
      // 关闭清空表单
      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>
