<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">强制回传EAS</el-button>
        <el-button slot="right" class="filter-item" type="success" icon="el-icon-s-promotion" size="mini" :disabled="isPushDisabled()" @click="handleBatchPush">下推出库</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 prop="bill_status" label="单据状态" width="90">
          <template slot-scope="scope">
            <el-tag :type="statusTagType(scope.row.bill_status)" size="mini">{{ billStatusFormat(scope.row.bill_status) }}</el-tag>
          </template>
        </el-table-column>
        <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 label="转发中鼎" align="center" prop="forwardZD" width="80">
          <template slot-scope="scope">
            <p v-if="scope.row.forwardZD == '0'">-</p>
            <template v-else-if="scope.row.forwardZD == '1'">
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon="el-icon-info" icon-color="red" title="是否重新转发中鼎？" @confirm="toForwardZD(scope.row)">
                <a slot="reference" style="color: red;text-decoration: underline">失败</a>
              </el-popconfirm>
            </template>
            <p v-else>成功</p>
          </template>
        </el-table-column>
        <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>
      <pagination />
    </div>
    <AddDialog @AddChanged="querytable" />
    <ViewDialog :dialog-show.sync="viewShow" :row-mst="mstrow" @AddChanged="querytable" />
  </div>
</template>

<script>
import crudPurchase from '@/views/wms/pm_manage/otherOut/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/pm_manage/purchase/AddDialog'
import ViewDialog from '@/views/wms/pm_manage/purchase/ViewDialog'

export default {
  name: 'OtherOut',
  components: { AddDialog, ViewDialog, crudOperation, rrOperation, udOperation, pagination },
  cruds() {
    return CRUD({
      title: '其他出库单',
      optShow: { add: true, reset: true },
      idField: 'id',
      url: '/api/purchasemst/108',
      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: {},
      multipleSelection: [],
      currentRow: null,
      audit_flag: true,
      billStatusOptions: [
        { value: '0', label: '已创建' },
        { value: '1', label: '执行中' },
        { value: '2', label: '已完成' }
      ]
    }
  },
  methods: {
    canUd(row) {
      return row.bill_status !== '0'
    },
    isPushDisabled() {
      // 没有选中、选中多行、或选中的行状态不是 '0' 时禁用
      if (this.multipleSelection.length !== 1) return true
      return this.multipleSelection[0].bill_status !== '0'
    },
    statusTagType(status) {
      const map = { '0': 'warning', '1': 'primary', '2': 'success' }
      return map[String(status)] || ''
    },
    billStatusFormat(bill_status) {
      const map = {
        '0': '已创建',
        '1': '下发',
        '2': '完成',
        '3': '审核成功',
        '4': '审核失败'
      };
      return map[bill_status] || 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
    },
    toForwardZD() {
      crudPurchase.pushZD({
        billid: row.bill_id,
        orderNo: row.order_no,
        orderType: row.order_type,
        red: row.red,
        status: row.status
      })
    },
    toView(index, row) {
      this.mstrow = row
      this.viewShow = true
    },
    handleSelectionChange(val, row) {
      console.log(val.length)
      if (val.length == 0) {
        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()
    },
    handleBatchPush() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请先勾选要下推的调拨出库单')
        return
      }
      // eslint-disable-next-line eqeqeq
      const invalidRows = this.multipleSelection.filter(item => String(item.bill_status) === '99')
      if (invalidRows.length) {
        this.$message.warning('仅支持批量下推状态为“分配”的需求单')
        return
      }
      this.$confirm(`确认批量下推已勾选的 ${this.multipleSelection.length} 条需求单吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudPurchase.outPush(this.multipleSelection[0]).then(res => {
          if (res.code === 200) {
            this.$message.success('下推成功')
            this.crud.toQuery()
          } else {
            this.$message.error(res.message)
          }
        }).catch(() => {
          this.$message.error('下推失败')
        })
      }).catch(() => {})
    },

    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>
