<template>
  <!-- 波次安排 -->
  <div class="wave-arrangement">
    <div class="search-box">
      <el-form
        :inline="true"
        :model="query"
      >
        <el-form-item label="订单开始日期">
          <el-date-picker
            v-model="query.orderStartDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            @change="queryTable"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单结束日期">
          <el-date-picker
            v-model="query.orderEndDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            @change="queryTable"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="业主名称">
          <el-select
            v-model="query.consignorId"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.consignorName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单据编号">
          <el-input
            v-model="query.orderNo"
            placeholder="请输入关键字"
            clearable
            @keyup.enter.native="queryTable"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="配送方向">
          <el-input
            v-model="query.companyMnemonic"
            placeholder="请输入关键字"
            clearable
            @keyup.enter.native="queryTable"
          ></el-input>
        </el-form-item>
        <el-form-item label="承运商">
          <el-input
            v-model="query.orderNo"
            placeholder="请输入关键字"
            clearable
            @keyup.enter.native="queryTable"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="出库库别">
          <el-select
            v-model="query.storageId"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="(item, index) in storageList"
              :key="index"
              :label="item.storageName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <rrOpt
            @query="toQuery"
            @reset="toReset"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="opt-box">
      <div class="opt-box-right">
        <span class="info-span">总订单数:{{ statisticsNum.totalOrderNumber }} 正常出库订单数:{{
            statisticsNum.normalOrderNumber
          }}
          <!-- 补货单据数:{{ statisticsNum.supplementOrderNumber }} 自提订单数:{{
            statisticsNum.ownOrderNumber
          }} -->
          异常订单数:{{ statisticsNum.abnormalOrderNumber }}</span>
        <el-button
          type="primary"
          :disabled="handleSelect.length === 0"
          @click="manageWave"
        >安排波次</el-button>
        <!-- <el-button
          type="primary"
          :disabled="handleSelect.length === 0"
          @click="toOrderPool"
          >订单池补货</el-button
        > -->
        <el-button
          type="primary"
          :disabled="handleSelect.length === 0"
          @click="toDistribute"
        >指定下发</el-button>
        <el-button
          type="primary"
          @click="toQuery"
        >刷新</el-button>
        <el-button
          type="primary"
          @click="exportSummary"
        >导入汇总</el-button>
        <el-button
          type="primary"
          @click="exportDetailed"
        >导入明细</el-button>
      </div>
    </div>
    <div class="layout-full">
      <heavy-table
        :data="tableData"
        :paging="paging"
        :loading="loading"
        :config="tableConfig"
        :tableProps="tableProps"
        @current-change="queryTable"
        @doDetail="doDetail"
        @handleselection="handleselection"
      >
      </heavy-table>
    </div>
    <orderPoolReplenishment
      ref="orderPoolReplenishment"
      dialogTitle="订单池补货"
      :idList="handleSelectId"
    />
    <designatedDistribute
      ref="designatedDistribute"
      :parent_detail_id="handleSelectId[0]"
      @doRefresh="toQuery"
    />
    <orderDetails
      ref="orderDetails"
      :orderInfo="orderInfo"
      @toReset="toReset"
    />
    <!-- 导入对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div
          class="el-upload__tip text-center"
          slot="tip"
        >
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >下载模板</el-link>
        </div>
      </el-upload>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitFileForm"
        >确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 安排波次 -->
    <el-dialog
      :close-on-click-modal="false"
      title="安排波次"
      :visible.sync="waveVisible"
      width="500px"
    >
      <sForm
        ref="simpleForm"
        :formdata="waveFormdata"
      > </sForm>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="waveVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmWave"
        >确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { consignorList } from '@/api/warehousing/acceptance'
import orderPoolReplenishment from './components/orderPoolReplenishment'
import designatedDistribute from './components/designatedDistribute'
import orderDetails from './components/orderDetails'
import { outOrderList, getOrderStatistics, waveSetGroup } from '@/api/exWarehouse/dispatchDistribute'
import { getStorageList } from '@/api/basicData/libraryType'
import { getToken } from '@/utils/auth'
export default {
  components: { orderPoolReplenishment, designatedDistribute, orderDetails },
  dicts: ['out_order_status', 'line_name_type', 'deliver_mode_dict', 'order_type_dict'],
  data() {
    const _that = this
    return {
      storageList: [],
      waveFormdata: {
        width: '115px',
        data: {
          storageCode: '',
          pickWay: ''
        },
        config: [
          {
            span: [24],
            dataProp: [
              [
                [
                  {
                    label: '选择出库区域:',
                    prop: 'storageCode',
                    type: 'selectCommon',
                    message: '请输入',
                    requireType: ['required'],
                    options: [],
                    span: 24,
                    show: true,
                    events: {
                      change: (v) => {
                        if (v === 'LX') {
                          this.$refs.simpleForm.setFormData(this.waveFormdata.config, true, 'pickWay', 'show')
                        } else {
                          this.$refs.simpleForm.setFormData(this.waveFormdata.config, false, 'pickWay', 'show')
                        }
                      }
                    }
                  },
                  {
                    label: '选择分拣方式:',
                    prop: 'pickWay',
                    type: 'selectCommon',
                    message: '请输入',
                    requireType: ['required'],
                    options: [
                      { label: 'U型拣选站', value: 'u' },
                      { label: '缓存墙', value: 'cache_wall' }
                    ],
                    span: 24,
                    show: false
                  }
                ]
              ]
            ]
          }
        ]
      },
      waveVisible: false,

      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: ''
      },
      handleSelect: [],
      handleSelectId: [],
      loading: false,
      query: {},
      tableData: [],
      paging: {
        page: 1, // 当前页
        size: 10, // 页面大小
        total: 0
      },
      tableConfig: [
        { label: '复选框', type: 'selection', prop: 'selection', istrue: true },
        {
          label: '序号',
          type: 'index',
          prop: 'index',
          istrue: true
        },
        {
          label: '业主编号',
          prop: 'consignorCode',
          istrue: true
          // width: "100",
        },
        {
          label: '业主名称',
          prop: 'consignorName',
          istrue: true
        },
        {
          label: '单位编号',
          prop: 'companyNo',
          istrue: true
        },
        {
          label: '单位名称',
          prop: 'companyName',
          istrue: true
        },
        {
          label: '单据编号',
          prop: 'orderNo',
          istrue: true
        },
        {
          label: '下单时间',
          prop: 'orderDate',
          istrue: true
        },
        // {
        //   label: '整件数',
        //   prop: 'totalCaseQry',
        //   istrue: true
        // },
        // {
        //   label: '折合件数',
        //   prop: 'combineNumber',
        //   istrue: true
        // },
        // {
        //   label: '出库优先级',
        //   prop: 'priority',
        //   istrue: true
        // },
        // {
        //   label: '客户备注',
        //   prop: 'companyRemark',
        //   istrue: true
        // },
        // {
        //   label: '开票员',
        //   prop: 'userSalesman',
        //   istrue: true
        // },
        // {
        //   label: '路线名称',
        //   prop: 'lineno',
        //   istrue: true,
        //   filter(row, value) {
        //     return _that.getDictLabel(value, _that.dict.type.line_name_type)
        //   }
        // },
        // {
        //   label: '提货方式',
        //   prop: 'deliverMode',
        //   istrue: true,
        //   filter(row, value) {
        //     return _that.getDictLabel(value, _that.dict.type.deliver_mode_dict)
        //   }
        // },
        // {
        //   label: '订单类型',
        //   prop: 'orderType',
        //   istrue: true,
        //   filter(row, value) {
        //     return _that.getDictLabel(value, _that.dict.type.order_type_dict)
        //   }
        // },
        // {
        //   label: '部门名称',
        //   prop: 'deptName',
        //   istrue: true
        // },
        // {
        //   label: '订单状态',
        //   prop: 'orderStatus',
        //   istrue: true,
        //   filter(row, value) {
        //     return _that.getDictLabel(value, _that.dict.type.out_order_status)
        //   }
        // },
        {
          label: '操作',
          prop: 'operating',
          istrue: true,
          type: 'button',
          width: 90,
          fixed: 'right',
          buttons: [
            {
              name: '订单详情',
              event: 'doDetail'
            }
          ]
        }
      ],
      options: [],
      tableProps: {
        // "max-height": 240,
      },
      statisticsNum: {},
      orderInfo: {}
    }
  },
  async created() {
    await this.getTableHeaderCom('busin_out_order_s', {
      config: this.tableConfig
    })
    this.getStorageList()
    this.queryTable()
    this.getBasicList()
    this.getStatistics()
  },
  methods: {
    // 查询库区id列表
    async getStorageList() {
      const { data } = await getStorageList()
      this.storageList = data
    },
    exportSummary() {
      this.upload.title = '汇总导入'
      this.upload.open = true
      this.upload.url = process.env.VUE_APP_BASE_API + '/wms/outOrder/s/importOrderS'
      // http://120.77.94.227:8010
    },
    exportDetailed() {
      this.upload.title = '明细导入'
      this.upload.open = true
      this.upload.url = process.env.VUE_APP_BASE_API + '/wms/outOrder/s/importOrderD'
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
    },
    /** 下载模板操作 */
    importTemplate() {
      if (this.upload.title === '汇总导入') {
        this.download('/wms/outOrder/s/importTemplateOrderS', {}, `exWarehouse_template_${new Date().getTime()}.xlsx`)
      } else {
        this.download('/wms/outOrder/s/importTemplateOrderD', {}, `exWarehouse_template_${new Date().getTime()}.xlsx`)
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 获取统计数
    getStatistics() {
      let request = {
        pageSize: this.paging.size,
        pageNum: this.paging.page,
        ...this.query
      }
      getOrderStatistics(request).then((res) => {
        if (res.code === 200) {
          this.statisticsNum = res.data
        }
      })
    },
    handleselection(data) {
      this.handleSelect = data
      this.handleSelectId = data.map((ele) => ele.id)
    },
    // 安排波次
    manageWave() {
      this.waveVisible = false
      this.$confirm('是否要安排所选波次?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let obj = {
          // ...this.waveFormdata.data,
          storageCode: 'LK001',
          ids: this.handleSelectId
        }
        waveSetGroup(obj).then((res) => {
          if (res.code == 200) {
            this.$message.success('波次安排成功')
            // this.toQuery();
            this.$emit('changeTab', '2')
          }
        })
      })
      // this.$nextTick(() => {
      //   this.$refs.simpleForm.setFormData(
      //     this.waveFormdata.config,
      //     this.storageList.map((e) => {
      //       return {
      //         label: e.storageName,
      //         value: e.storageCode
      //       }
      //     }),
      //     'storageCode'
      //   )
      //   this.$refs.simpleForm.resetFormValue()
      // })
    },
    confirmWave() {
      this.$refs.simpleForm.validate((valid) => {
        if (!valid) return
        let obj = {
          ...this.waveFormdata.data,
          ids: this.handleSelectId
        }
        waveSetGroup(obj).then((res) => {
          if (res.code == 200) {
            this.$message.success('波次安排成功')
            // this.toQuery();
            this.$emit('changeTab', '2')
          }
        })
      })
    },
    toOrderPool() {
      this.$refs.orderPoolReplenishment.dialogVisible = true
    },
    toDistribute() {
      if (this.handleSelect.length > 1) {
        this.$message.warning('只能选择一项订单指定下发')
      } else {
        this.$refs.designatedDistribute.dialogVisible = true
      }
    },
    doDetail(row) {
      this.$refs.orderDetails.dialogVisible = true
      this.orderInfo = row
    },
    toQuery() {
      // this.paging.page = 1;
      // this.queryTable();
    },
    toReset() {
      this.query = {}
      this.queryTable()
    },
    queryTable() {
      this.loading = true
      let request = {
        pageSize: this.paging.size,
        pageNum: this.paging.page,
        ...this.query
      }
      outOrderList(request)
        .then((res) => {
          if (res.code === 200) {
            let arr = res.rows
            // arr.forEach((element, index) => {
            //   this.$set(arr, index, {
            //     ...element,
            //     ...element.baseAddress,
            //     ...element.baseCompany,
            //     ...element.baseConsignor,
            //   });
            // });
            this.tableData = arr
            this.paging.total = res.total
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    getBasicList() {
      consignorList().then((res) => {
        this.options = res.rows
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.info-span {
  margin-right: 10px;
}
</style>
