<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :exportList="exportList"
 
    :tableAttributes="tableAttributes"
    :tableEvents="tableEvents"
    :optionsEvensGroup="optionsEvensGroup"
    :columnParsing="columnParsing"
  >
    <template #moreSearch>
      <div style="margin-bottom: 20px">
        <div class="num" style="margin: 0">当前列表总发货数量：{{ totalNum.invoiceNumber }}</div>
        <div class="num">总含税金额：{{ totalNum.payAmount | toThousandFilter }}</div>
      </div>
    </template>
    <Popu v-if="isShow !== 1">
      <apply-return-form v-if="isShow === 2" @backListFormDetail="backList" />
      <engin-return-form v-if="isShow === 3" @backListFormDetail="backList" />
    </Popu>
    <print-preview ref="preView" @initPrint="handleInitPrint" @refreshList="handleRefreshList" :addPrint="addPrint"/>
    <el-dialog
      title="密码确认"
      :visible.sync="isShowDialog"
      :show-close="false"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form ref="dialogForm" :model="dialogForm" :rules="dialogFormRules" label-position="right" label-width="70px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="密码" prop="password">
              <el-input v-model="dialogForm.password" autocomplete="off" placeholder="请输入密码" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="12">
            <el-form-item label="操作人" prop="createMan">
              <el-input v-model="dialogForm.createMan" readonly />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="12" style="height: 51px">
            <el-form-item label="操作日期" prop="createDate">
              <el-date-picker
                v-model="dialogForm.createDate"
                readonly
                type="date"
                value-format="yyyy-MM-dd"
                style="width: 100%"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialogForm">取 消</el-button>
        <el-button type="primary" @click="submitDialogForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="导出项" :visible.sync="dialogVisible" width="50%">
      <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0" />
      <el-checkbox-group v-model="check" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="item in excelData" :label="item.value">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import add_callback_mixin from '@/components/template/add_callback_mixin.js'
import Popu from '@/components/template/popu.vue'
import { getSumList, getSumListV2, exportSumListV2 } from '@/api/supply/deliver'
import print from '@/mixin/print'
import { checkPassword, getListInvoiceNumber, getListInvoiceNumberV2 } from '@/api/supply/pickup'
import { getCategoryList, getSalesmanList } from '@/api/common'
import SumPrint from '@/views/supply/deliver/components/sum_print'
import { getWarehouseList } from '@/api/supply/apply'
import ApplyReturnForm from './components/apply_return_form.vue'
import EnginReturnForm from './components/engin_return_form.vue'
import printPreview from './components/design/preview.vue'
export default {
  components: { TemplatePage, Popu, SumPrint, ApplyReturnForm, EnginReturnForm, printPreview },
  mixins: [import_mixin, add_callback_mixin, print],
  data() {
    return {
      visible: false,
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '打印发货单',
              click: () => {
                if (this.recordSelected.length === 0) {
                  this.$message.error('请选择需要删除的数据')
                  return
                }
                this.toPrint()
              }
            }
          ]
        ],
        [
          [
            {
              name: '零售退货申请',
              click: () => {
                this.isShow = 2
              },
              isRole: this.$checkBtnRole('refund', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '工程退货申请',
              click: () => {
                this.isShow = 3
              },
              isRole: this.$checkBtnRole('refund', this.$route.meta.roles)
            }
          ]
        ]
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      }, // 关闭新增弹窗

      // 表格事件
      tableEvents: {
        'selection-change': this.handleSelect
      },
      recordSelected: [],
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: null, // 列表数据
      listLoading: false, // 列表加载loading
      screenForm: {
        // 筛选表单数据
        goodsName: '',
        goodsCode: '',
        goodsOldCode: '',
        model: '',
        createDate: [],
        deliverDate: [],
        correspondId: [],
        jxsNum: '',
        jxsName: '',
        orderNum: '',
        type: '',
        salesMan: '',
        k3ServiceId: '',
        mainOrderId: '',
        approvaTime: [],
        types: '',
        printStatus: '',
        discriminate: '',
        refEnginRecordNo: '',
        invoicePrintStatus: '',
        createBy: ''
      },
      invoiceList: [
        {
          value: 1,
          label: '申请发货单'
        },
        {
          value: 2,
          label: '退货单'
        },
        {
          value: 3,
          label: '直调发货单'
        }
      ],
      categoryList: [],
      salesmanList: [],
      tableSelection: [],
      queryItem: {},
      isShowPrint: false,
      totalNum: {},
      isShowDialog: false,
      dialogForm: {
        password: '',
        createMan: '',
        createDate: ''
      },
      warehouseList: [],
      dialogFormRules: {
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      dialogVisible: false,
      excelData: [
        {
          value: 1,
          name: '状态'
        },
        {
          value: 2,
          name: '打印时间'
        }
      ],
      check: [],
      checkAll: false,
      isCollapse: true,
      isIndeterminate: false,
      isShow: 1
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.initPrint()
    })
  },
  methods: {
    // 列表请求函数
    getList(...p) {
      this.recordSelected = []
      getListInvoiceNumberV2( ...p ).then(res => {
        this.totalNum = res.data
      })
      return getSumListV2(...p)
    },
    // 列表导出函数
    exportList: exportSumListV2,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    operation() {
      return (h, { row, index, column }) => {
        return <div class="operation-btns"></div>
      }
    },
    handleClose() {
      this.addOff(() => {
        this.visible = false
      })()
    },
    handleFilterData() {
      this.dialogVisible = true
    },

    handleCheckAllChange(val) {
      const arr = []
      if (val) {
        for (let i = 1; i <= this.excelData.length; i++) {
          arr.push(i)
        }
      }
      this.check = val ? arr : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange() {
      console.log(this.checkAll)
    },
    // 获取业务员列表
    getSalesmanList() {
      getSalesmanList({
        pageNum: 1,
        pageSize: -1,
        isCustomer: 0,
        status: true
      }).then(res => {
        this.salesmanList = res.data.records
      })
    },

    // 获取存货类别列表
    getCategoryList() {
      getCategoryList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.categoryList = res.data.records
      })
    },
    // 获取仓库列表
    getWarehouseList() {
      getWarehouseList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.warehouseList = res.data.records
      })
    },
    // // 查询列表
    // getList() {
    //   this.listLoading = true
    //   const params = {
    //     pageNum: this.currentPage,
    //     pageSize: this.pageSize,
    //     materialName: this.screenForm.goodsName,
    //     materialNumber: this.screenForm.goodsCode,
    //     materialOldNumber: this.screenForm.goodsOldCode,
    //     specification: this.screenForm.model,
    //     printStatus: this.screenForm.printStatus,
    //     invoicePrintStatus: this.screenForm.invoicePrintStatus,
    //     discriminate: this.screenForm.discriminate,
    //     createBy: this.screenForm.createBy,

    //     refEnginRecordNo: this.screenForm.refEnginRecordNo,

    //     createStartTime: this.screenForm.createDate ? this.screenForm.createDate[0] : '',
    //     createEndTime: this.screenForm.createDate ? this.screenForm.createDate[1] : '',
    //     startTime: this.screenForm.deliverDate ? this.screenForm.deliverDate[0] : '',
    //     endTime: this.screenForm.deliverDate ? this.screenForm.deliverDate[1] : '',
    //     customerNumber: this.screenForm.jxsNum,
    //     customerName: this.screenForm.jxsName,
    //     id: this.screenForm.orderNum,
    //     categoryName: this.screenForm.type,
    //     serviceId: this.screenForm.salesMan,
    //     k3ServiceId: this.screenForm.k3ServiceId,
    //     mainOrderId: this.screenForm.mainOrderId,
    //     approvalEndTime: this.screenForm.approvaTime ? this.screenForm.approvaTime[1] : '',
    //     approvalStartTime: this.screenForm.approvaTime ? this.screenForm.approvaTime[0] : '',
    //     correspondId: this.screenForm.correspondId.join(','),
    //     type: this.screenForm.types
    //   }

    //   getSumList(params).then(res => {
    //     res.data.records.forEach(item => {
    //       item.notOutNumber = item.salesStatus ? 0 : item.refundableQty
    //       item.sums1 = ['refundableQty', 'compute_wckNum']
    //       item.sums2 = [
    //         'payAmount',
    //         'payRebateAmount',
    //         'discAmount',
    //         'totalDiscAmount',
    //         'singlePayPrice',
    //         'compute_zkeAmount'
    //       ]
    //     })
    //     this.dataList = res.data.records
    //     this.listTotal = res.data.total
    //     this.listLoading = false
    //   })
    //   this.getListInvoiceNumber()
    // },

    getListInvoiceNumber() {
      const params = {
        materialName: this.screenForm.goodsName,
        materialNumber: this.screenForm.goodsCode,
        materialOldNumber: this.screenForm.goodsOldCode,
        specification: this.screenForm.model,
        printStatus: this.screenForm.printStatus,
        invoicePrintStatus: this.screenForm.invoicePrintStatus,
        discriminate: this.screenForm.discriminate,
        createBy: this.screenForm.createBy,
        refEnginRecordNo: this.screenForm.refEnginRecordNo,
        createStartTime: this.screenForm.createDate ? this.screenForm.createDate[0] : '',
        createEndTime: this.screenForm.createDate ? this.screenForm.createDate[1] : '',
        startTime: this.screenForm.deliverDate ? this.screenForm.deliverDate[0] : '',
        endTime: this.screenForm.deliverDate ? this.screenForm.deliverDate[1] : '',
        customerNumber: this.screenForm.jxsNum,
        customerName: this.screenForm.jxsName,
        id: this.screenForm.orderNum,
        categoryName: this.screenForm.type,
        serviceId: this.screenForm.salesMan,
        k3ServiceId: this.screenForm.k3ServiceId,
        mainOrderId: this.screenForm.mainOrderId,
        approvalEndTime: this.screenForm.approvaTime ? this.screenForm.approvaTime[1] : '',
        approvalStartTime: this.screenForm.approvaTime ? this.screenForm.approvaTime[0] : '',
        correspondId: this.screenForm.correspondId.join(','),
        type: this.screenForm.types
      }
      getListInvoiceNumber(params).then(res => {
        // console.log(res,'ii');
        this.totalNum = res.data
      })
    },
    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1
      this.$refs.pageRef.refreshList()
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields()
      this.currentPage = 1
      this.$refs.pageRef.refreshList()
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.$refs.pageRef.refreshList()
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.$refs.pageRef.refreshList()
    },

    handleSelect(data) {
      this.recordSelected = data
      // console.log(selection,row);
      // this.$refs.table.toggleRowSelection(row)
      // this.dataList.forEach(item => {
      //   if (item.id === row.id) {
      //     this.$refs.table.toggleRowSelection(item)
      //   }
      // })
      // this.tableSelection = this.$refs.table.selection
      this.tableSelection = data
    },



    // 点击打印
    toPrint() {
      this.queryItem = this.tableSelection
      if (this.tableSelection.every(e => e.printNum == 0)) {
        this.queryItem = this.tableSelection
        this.getDateil(this.tableSelection, 'getDeliverDetail').then(res => {
          this.$endLoading()
          this.$refs.preView.show(this.hiprintTemplate, this.outputData)
        })
      } else {
        this.queryItem = this.tableSelection
        this.dialogForm.createMan = JSON.parse(localStorage.getItem('supply_user')).nickName
        this.dialogForm.createDate = this.getDate()
        this.isShowDialog = true
      }
    },

    // 关闭弹窗
    cancelDialogForm() {
      this.isShowDialog = false
      this.$refs.dialogForm.resetFields()
    },

    // 提交 弹窗
    submitDialogForm() {
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          const params = {
            shipId: this.queryItem[0].invoiceId,
            password: this.dialogForm.password
          }
          checkPassword(params).then(res => {
            this.getDateil(this.tableSelection, 'getDeliverDetail').then(res => {
              this.$endLoading()
              this.$refs.preView.show(this.hiprintTemplate, this.outputData)
            })
            this.cancelDialogForm()
          })
        }
      })
    },

    getDate() {
      var date = new Date()
      var seperator1 = '-'
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate
      return currentdate
    },

    backList() {
      this.isShow = 1
      this.$refs.pageRef.refreshList()
    }
    ,
    handleRefreshList(){
      this.recordSelected = []
      this.tableSelection = []
      this.$refs.pageRef.refreshList()
      console.log(999);
    },
    handleInitPrint(){
      this.$nextTick(() => {
      this.initPrint()
    })
    }
  }
}
</script>

<style lang="scss" scoped>
.num {
  display: inline-block;
  font-size: 16px;
  margin-left: 20px;
  color: #909399;
  vertical-align: middle;
}
</style>
