<template>
  <div style="padding-bottom:30px">
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['purchaseWarehousing:add'])" type="primary"
            @click="handleAddPurchaseWarehousing">新增</el-button>
          <el-button size="mini" v-if="checkPermission(['purchaseWarehousing:del'])" @click="handleDeletePurchaseWarehousing()"
            type="danger" :disabled="multipleSelection.length === 0">删除</el-button>
          <el-button size="mini" v-if="checkPermission(['purchaseWarehousing:audit'])"
            @click="handleAuditsPurchaseWarehousing()" type="success"
            :disabled="multipleSelection.length === 0">批量审核</el-button>
          <el-button type="success" size="mini" v-if="checkPermission(['purchaseWarehousing:submit'])"
            @click="handleSubmitPurchaseWarehousings()" :disabled="multipleSelection.length === 0">批量提交</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" placeholder="请输入库单号" advanced
            advancedWidth="465">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="所属部门">
                  <el-cascader v-model="advancedForm.dept_id" :options="deptList" :props="{
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    checkStrictly: true
                  }" clearable></el-cascader>
                </el-form-item>
                <el-form-item label="仓库">
                  <el-select v-model="advancedForm.warehouse_id">
                    <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="供应商" prop="supplier_id">
                  <el-select v-model="advancedForm.supplier_id">
                    <el-option v-for="item in supplierList" :key="item.id" :label="item.custom_name" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="advancedForm.status">
                    <el-option key="NotSubmit" label="未提交" value="NotSubmit" />
                    <el-option key="Submit" label="已提交" value="Submit" />
                    <el-option key="AuditPass" label="审核通过" value="AuditPass" />
                    <el-option key="AuditReject" label="审核驳回" value="AuditReject" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker v-model="advancedForm.purchasePlan_time_range" type="daterange" align="center"
                    :editable="false" unlink-panels :clearable="true" :default-time="['00:00:00', '23:59:59']"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                    :picker-options="{ disabledDate(time) { return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1 }, shortcuts: MixinPickerShortcuts }">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sn" label="入库单编号">
          <template slot-scope="scope">
            <router-link style="color: #409eff;"
              v-if="checkPermission(['purchaseWarehousing'])"
              :to="{ name: 'purchaseWarehousingDetail', params: { id: scope.row.id } }">{{ scope.row.sn }}</router-link>
            <span v-else>{{scope.row.sn}}</span>
          </template>
        </el-table-column>
        <el-table-column label="入库日期">
          <template slot-scope="scope">{{ scope.row.entry_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column prop="dept_name" label="所属部门" />
        <el-table-column prop="warehouse_name" label="仓库" />
        <el-table-column prop="supplier_name" label="供应商" />
        <el-table-column prop="plate_number" label="车牌号" />
        <el-table-column prop="handled_by_name" label="经手人" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">{{ statusFilter(scope.row.status) }}</template>
        </el-table-column>
        <el-table-column prop="audit_by" label="审核人" />
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="success" size="mini"
              v-if="scope.row.allowable.submit && checkPermission(['purchaseWarehousing:submit'])"
              @click="handleSubmitPurchaseWarehousing(scope.row)">提交</el-button>
            <el-button type="danger" size="mini"
              v-else-if="scope.row.allowable.withdraw && checkPermission(['purchaseWarehousing:withdraw'])"
              @click="handleWithdrawPurchaseWarehousing(scope.row)">撤回</el-button>
            <el-button type="success" size="mini"
              v-if="scope.row.allowable.audit && checkPermission(['purchaseWarehousing:audit'])"
              @click="handleAuditPurchaseWarehousing(scope.row)">审核</el-button>
            <el-button size="mini" v-if="scope.row.allowable.edit && checkPermission(['purchaseWarehousing:edit'])"
              @click="handleEditPurchaseWarehousing(scope.row)">编辑</el-button>
            <el-button type="primary" v-if="checkPermission(['purchaseWarehousing:print'])" size="mini"
              @click="handlePrintPurchaseWarehousingDialog(scope.row)">打印</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>

    <el-dialog title="采购入库表" :visible.sync="dialogVisible" width="840px" center>
      <el-button size="mini" type="primary" @click="handlePrintPurchaseWarehousing" class="print">打印</el-button>
      <div id="deliverySheet" style="width:800px">
        <div class="tips-t">
          <div>
            仓库名称编码:{{ purchaseWarehousingForm.dept_name }}{{ purchaseWarehousingForm.warehouse_name }}
          </div>
          <div>
            日期:{{ purchaseWarehousingForm.entry_time | unixToDateStr }}
          </div>
          <div>
            编号:{{ purchaseWarehousingForm.sn }}
          </div>
        </div>
        <el-table :data="purchaseWarehousingForm.product_list" border :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center', background: '#f4f4f4' }"
          style="width: 800px; margin:0 auto;margin-top: 20px;">
          <el-table-column label="产品编码">
            <template slot-scope="scope">
              {{ scope.row.sn }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号">
            <template slot-scope="scope">
              {{ scope.row.specification }}
            </template>
          </el-table-column>
          <el-table-column label="产品名称">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column label="单位">
            <template slot-scope="scope">
              {{ scope.row.unit }}
            </template>
          </el-table-column>
          <el-table-column label="数量">
            <template slot-scope="scope">
              {{ scope.row.num }}
            </template>
          </el-table-column>
        </el-table>
        <div class="tips-t">
          <div>
            送货车辆车牌号:{{ purchaseWarehousingForm.plate_number }}
          </div>
          <div>
            送货单号:{{ purchaseWarehousingForm.delivery_number }}
          </div>
          <div>
            制单人:{{ purchaseWarehousingForm.handled_by_name }}
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="批量审核" :visible.sync="multipleVisible" width="500px" center>
      <span>请选择审核状态：</span>
      <el-radio v-model="auditStatus" label="AuditPass">通过</el-radio>
      <el-radio v-model="auditStatus" label="AuditReject">驳回</el-radio>
      <div class="btn-box">
        <el-button type="" @click="multipleVisible = false">取消</el-button>
        <el-button type="primary" @click="auditPurchaseWarehousing">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Purchase from '@/api/purchase'
import Print from 'print-js'
import * as API_Setting from '@/api/setting'
import { Foundation } from '~/ui-utils'
import * as API_BasicSetting from '@/api/basicSetting'
export default {
  name: 'purchasePlan',
  data() {
    return {
      deptList: [],
      supplierList: [],
      warehouseList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: '',
      dialogVisible: false,
      // 当前已选择的行
      multipleSelection: [],
      purchaseWarehousingForm: {},
      // 批量审核弹窗显隐
      multipleVisible: false,
      // 批量审核状态
      auditStatus: 'AuditPass'
    }
  },
  mounted() {
    this.GET_PurchaseWarehousingList()
    this.GET_DeptList()
    this.GET_SupplierList()
    this.GET_WarehouseList()
  },
  watch: {
    $route: function({ query }) {
      this.params.page_no = 1
      this.GET_PurchaseWarehousingList()
    }
  },
  methods: {
    /** 获取仓库 */
    GET_WarehouseList(e) {
      API_BasicSetting.getWarehouseListAll(e).then(response => {
        this.warehouseList = response
      })
    },
    /** 获取供应商 */
    GET_SupplierList() {
      API_BasicSetting.getSupplierListAll().then(response => {
        this.supplierList = response
      })
    },
    handleAuditsPurchaseWarehousing() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.multipleVisible = true
    },
    /** 批量审核提交 */
    auditPurchaseWarehousing() {
      const ids = this.multipleSelection.map(item => item.id)
      API_Purchase.auditPurchaseWarehousing(ids, { status: this.auditStatus }).then(() => {
        this.$message.success('提交成功')
        this.multipleVisible = false
        this.GET_PurchaseWarehousingList()
      })
    },
    handleSubmitPurchaseWarehousings() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定要提交这些采购入库吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_Purchase.submitPurchaseWarehousing(ids).then(() => {
          this.$message.success('提交成功！')
          this.GET_PurchaseWarehousingList()
        })
      }).catch(() => { })
    },
    handleSubmitPurchaseWarehousing(row) {
      API_Purchase.submitPurchaseWarehousing(row.id).then(() => {
        this.$message.success('提交成功！')
        this.GET_PurchaseWarehousingList()
      })
    },
    handleWithdrawPurchaseWarehousing(row) {
      API_Purchase.withdrawPurchaseWarehousing(row.id).then(() => {
        this.$message.success('撤回成功！')
        this.GET_PurchaseWarehousingList()
      })
    },
    /** 入库单状态 */
    statusFilter(val) {
      switch (val) {
        case 'NotSubmit':
          return '未提交'
        case 'Submit':
          return '已提交'
        case 'AuditPass':
          return '审核通过'
        case 'AuditReject ':
          return '审核驳回'
        default:
          return ''
      }
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 打印对账详情 */
    handlePrintPurchaseWarehousing() {
      Print({
        printable: 'deliverySheet',
        type: 'html',
        targetStyles: ['*'],
        ignoreElements: ['no-logs', 'goods-image', 'no-btn']
      })
    },
    handleDeletePurchaseWarehousing() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定要删除这些采购入库吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_Purchase.deletePurchaseWarehousing(ids).then(() => {
          this.$message.success('删除成功！')
          this.GET_PurchaseWarehousingList()
        })
      }).catch(() => { })
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_PurchaseWarehousingList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_PurchaseWarehousingList()
    },

    /** 添加采购入库 */
    handleAddPurchaseWarehousing() {
      this.$router.push({
        name: 'purchaseWarehousingAdd',
        params: { callback: this.GET_PurchaseWarehousingList }
      })
    },
    /** 编辑采购入库 */
    handleEditPurchaseWarehousing(row) {
      this.$router.push({
        name: 'purchaseWarehousingEdit',
        params: { id: row.id }
      })
    },
    /** 审核采购入库 */
    handleAuditPurchaseWarehousing(row) {
      this.$router.push({
        name: 'purchaseWarehousingAudit',
        params: { id: row.id }
      })
    },
    /** 打印采购入库 */
    handlePrintPurchaseWarehousingDialog(row) {
      this.GET_PurchaseWarehousingDetail(row.id)
    },
    /** 获取采购入库详情页面数据 */
    GET_PurchaseWarehousingDetail(id) {
      API_Purchase.getPurchaseWarehousingInfo(id).then(response => {
        this.purchaseWarehousingForm = response
        this.dialogVisible = true
      })
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data
      }
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key])
      this.params.page_no = 1
      this.GET_PurchaseWarehousingList()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.purchasePlan_time_range) {
        this.params.entry_time_begin = parseInt(Number(this.advancedForm.purchasePlan_time_range[0]) / 1000)
        this.params.entry_time_end = parseInt(Number(this.advancedForm.purchasePlan_time_range[1]) / 1000)
      }
      delete this.params.purchasePlan_time_range
      this.params.page_no = 1
      this.GET_PurchaseWarehousingList()
    },
    /** 获取采购入库列表 */
    GET_PurchaseWarehousingList() {
      this.loading = true
      API_Purchase.getPurchaseWarehousingList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.print {
  margin-left: 740px;
}
.btn-box {
  text-align: center;
  margin: 30px 0 10px;
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    text-align: center;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
