<template>
  <div class="app-container">
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-form :inline="true" class="demo-form-inline" label-position="right" label-width="80px" label-suffix=":">
          <el-form-item label="模糊查询">
            <el-input v-model="query.blurry" size="mini" clearable placeholder="单据号/订单号/供应商" @keyup.enter.native="crud.toQuery" />
          </el-form-item>
          <el-form-item label="单据编号">
            <el-input v-model="query.bill_id" size="mini" clearable placeholder="单据编号" @keyup.enter.native="crud.toQuery" />
          </el-form-item>
          <el-form-item label="订单号">
            <el-input v-model="query.order_no" size="mini" clearable placeholder="订单号" @keyup.enter.native="crud.toQuery" />
          </el-form-item>
          <el-form-item label="供应商">
            <el-input v-model="query.supplier_name" size="mini" clearable placeholder="供应商名称" @keyup.enter.native="crud.toQuery" />
          </el-form-item>
          <el-form-item label="单据状态">
            <el-select v-model="query.bill_status" clearable size="mini" placeholder="全部" class="filter-item" @change="crud.toQuery">
              <el-option v-for="item in billStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker v-model="query.createTime" type="daterange" value-format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" @change="crud.toQuery" />
          </el-form-item>
          <rrOperation />
        </el-form>
      </div>
      <crudOperation :permission="permission">
        <el-button slot="right" class="filter-item" type="warning" icon="el-icon-s-promotion" size="mini" :disabled="audit_flag" @click="issueReturnBill">下发回传单</el-button>
      </crudOperation>
      <el-table ref="table" v-loading="crud.loading" size="mini" :data="crud.data" highlight-current-row style="width: 100%;" @selection-change="crud.selectionChangeHandler" @current-change="handleCurrentChange" @select="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column v-permission="['admin','purchasemst:del','purchasemst:edit']" label="操作" width="115" align="center" fixed="right">
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" :disabled-edit="canUd(scope.row)" :disabled-dle="canUd(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="bill_id" width="160" label="单据编号">
          <template slot-scope="scope">
            <el-link type="warning" @click="toView(scope.$index, scope.row)">{{ scope.row.bill_id }}</el-link>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="order_no" width="150" label="订单号" />
        <el-table-column show-overflow-tooltip prop="order_type" width="100" label="订单类型" />
        <el-table-column :formatter="billStatusFormat" prop="bill_status" width="100" label="单据状态" />
        <el-table-column label="明细数" align="center" prop="dtl_count" width="80" />
        <el-table-column label="单据总数" align="center" prop="total_qty" width="80" />
        <el-table-column label="入库数量" align="center" prop="instock_qty" width="80" />
        <el-table-column show-overflow-tooltip prop="supplier_code" width="120" label="供应商编码" />
        <el-table-column show-overflow-tooltip prop="supplier_name" width="150" label="供应商名称" />
        <el-table-column show-overflow-tooltip prop="creator" width="100" label="创建人" />
        <el-table-column show-overflow-tooltip prop="create_time" width="150" label="创建时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="modify_date" width="150" label="修改时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.modify_date) }}
          </template>
        </el-table-column>
<!--        <el-table-column prop="status" :formatter="auditStatusFormat" width="100" label="审核状态" />-->
<!--        <el-table-column show-overflow-tooltip prop="audit_msg" width="150" label="审核信息" />-->
      </el-table>
      <pagination />
    </div>
    <AddDialog @AddChanged="querytable" />
    <ViewDialog :dialog-show.sync="viewShow" :row-mst="mstrow" @AddChanged="querytable" />
  </div>
</template>

<script>
import crudPurchase from '@/views/wms/st/purchase/purchase'
import CRUD, { crud, header, presenter } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import AddDialog from '@/views/wms/st/purchase/AddDialog'
import ViewDialog from '@/views/wms/st/purchase/ViewDialog'

export default {
  name: 'Purchase',
  components: { AddDialog, ViewDialog, crudOperation, rrOperation, udOperation, pagination },
  cruds() {
    return CRUD({
      title: '采购入库单',
      optShow: { add: true, reset: true },
      idField: 'id',
      url: '/api/purchasemst',
      crudMethod: { ...crudPurchase },
      queryOnPresenterCreated: true
    })
  },
  mixins: [presenter(), header(), crud()],
  data() {
    return {
      permission: {
        add: ['admin', 'purchasemst:add'],
        edit: ['admin', 'purchasemst:edit'],
        del: ['admin', 'purchasemst:del']
      },
      viewShow: false,
      mstrow: {},
      currentRow: null,
      audit_flag: true,
      billStatusOptions: [
        { value: '0', label: '已创建' },
        { value: '1', label: '执行中' },
        { value: '2', label: '已完成' }
      ]
    }
  },
  methods: {
    canUd(row) {
      return row.bill_status !== '0'
    },
    billStatusFormat(row) {
      const map = { '0': '已创建', '1': '执行中', '2': '已完成' }
      return map[row.bill_status] || row.bill_status
    },
    auditStatusFormat(row) {
      const map = { '0': '未审核', '1': '已审核' }
      return map[row.status] || row.status || '-'
    },
    formatDate(val) {
      if (!val) return ''
      if (typeof val === 'string') return val
      const d = new Date(val)
      const y = d.getFullYear()
      const m = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const h = String(d.getHours()).padStart(2, '0')
      const min = String(d.getMinutes()).padStart(2, '0')
      const s = String(d.getSeconds()).padStart(2, '0')
      return y + '-' + m + '-' + day + ' ' + h + ':' + min + ':' + s
    },
    toView(index, row) {
      this.mstrow = row
      this.viewShow = true
    },
    handleSelectionChange(val, row) {
      console.log(val.length)
      if (val.length == 0) {
        // this.$refs.table.clearSelection()
        // this.$refs.table.toggleRowSelection(val.pop())
        this.audit_flag = true
      }else {
        this.audit_flag = false
      }
    },

    handleCurrentChange(currentRow) {
      if (currentRow === null) {
        this.currentRow = {}
      } else {
        this.currentRow = currentRow
      }
      this.audit_flag = this.crud.selections.length === 0
    },
    querytable() {
      this.crud.toQuery()
    },
    issueReturnBill() {
      const selections = this.crud.selections
      if (!selections || selections.length === 0) {
        this.crud.notify('请至少选择一条单据', CRUD.NOTIFICATION_TYPE.INFO)
        return
      }
      const ids = selections.map(s => s.id)
      const billIds = selections.map(s => s.bill_id).join('、')
      this.$confirm('确认下发以下单据的回传单？\n' + billIds, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudPurchase.issueReturnBill(ids).then(() => {
          this.crud.notify('下发成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.toQuery()
        }).catch(() => {
          this.crud.notify('下发失败', CRUD.NOTIFICATION_TYPE.ERROR)
        })
      }).catch(() => {})
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-dialog__body {
  padding-top: 10px;
}
</style>
