<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="5em">
      <el-form-item label="计划跟踪号" prop="erpMtoNo" label-width="6em">
        <el-input
          v-model="queryParams.erpMtoNo"
          placeholder="请输入计划跟踪号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编号" prop="erpBillNo">
        <el-input
          v-model="queryParams.erpBillNo"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否返工" prop="erpIsRework">
        <el-radio-group v-model="queryParams.erpIsRework">
          <el-radio :label="null">全部</el-radio>
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="生产车间" prop="deptId">
        <dept-select v-model="queryParams.deptId" @change="handleQuery"/>
      </el-form-item>
      <el-form-item label="物料" prop="materialNumber">
        <el-input v-model="queryParams.materialNumber" placeholder="请输入物料" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="erpStatusList">
        <el-checkbox-group v-model="queryParams.erpStatusList" @change="handleQuery">
          <el-checkbox-button
            v-for="dict in dict.type.prod_order_erp_status"
            :key="dict.value"
            :label="dict.value"
          >{{dict.label}}
          </el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-has-permi="['yh:prodOrder:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-has-permi="['yh:prodOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-has-permi="['yh:prodOrder:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleSync"
          v-has-permi="['yh:prodOrder:sync']"
        >同步</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table size="mini" max-height="600px" v-loading="loading" :data="prodOrderList" @selection-change="handleSelectionChange" :default-sort="defaultSort"  @sort-change="onSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="column of showColumns">
        <el-table-column
            :key="column.key"
            :label="column.label"
            :prop="column.key"
            :align="column.align"
            :min-width="column.minWidth"
            :sort-orders="orderSorts"
            :sortable="column.sortable"
            :show-overflow-tooltip="column.overflow"
            :width="column.width"
        >
          <template slot-scope="d">
            <template v-if="column.key === 'id'">
              {{d.row[column.key]}}
            </template>
            <template v-else-if="column.key === 'erpDocumentStatus'">
              <dict-tag :options="dict.type.prod_order_erp_document_status" :value="d.row[column.key]" size="mini"/>
            </template>
            <template v-else-if="column.key === 'erpStatus'">
              <dict-tag :options="dict.type.prod_order_erp_status" :value="d.row[column.key]" size="mini"/>
            </template>
            <template v-else-if="column.key === 'erpReqSrc'">
              <dict-tag :options="dict.type.prod_order_erp_req_src" :value="d.row[column.key]" size="mini"/>
            </template>
            <template v-else-if="column.key === 'erpIsRework'">
              <boolean-tag :value="d.row.erpIsRework" size="mini"/>
            </template>
            <template v-else-if="column.key === 'percentage'">
              <prod-order-progress :percentage="percentage(d.row)" width="100%" />
              <div>数量:{{d.row.erpQty | dv}} {{d.row.unitName}} </div>
              <div>未入库:{{d.row.erpNoStockInQty | dv}} {{d.row.unitName}}</div>
            </template>
            <template v-else-if="['erpQty', 'erpNoStockInQty'].includes(column.key)">
              {{d.row[column.key]}}
              <template v-if="!isEmpty(d.row.unitName)">{{d.row.unitName}}</template>
            </template>
            <template v-else-if="column.key === 'time'">
              <template v-if="d.row.erpDate">单据日期:{{d.row.erpDate | dv}}<br/></template>
              <!-- <template v-if="d.row.erpCreateDate">创建:{{d.row.erpCreateDate | dv}}<br/></template>
              <template v-if="d.row.erpModifyDate">修改:{{d.row.erpModifyDate | dv}}<br/></template> -->
              <template v-if="d.row.erpConveyDate">下达:{{d.row.erpConveyDate | dv}}<br/></template>
              <template v-if="d.row.syncTime">同步:{{d.row.syncTime | dv}}<br/></template>
            </template>
            <template v-else>
              {{d.row[column.key]}}
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-has-permi="['yh:prodOrder:edit']"-->
<!--          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-has-permi="['yh:prodOrder:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-has-permi="['yh:prodOrder:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleSync({id: scope.row.erpId})"
            v-has-permi="['yh:prodOrder:sync']"
          >同步</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import {
  addProdOrder,
  delProdOrder,
  getProdOrder,
  listProdOrder,
  syncProdOrder,
  updateProdOrder
} from "@/api/yh/prodOrder";
import {$showColumns} from '@/utils/mixins';
import FormCol from "@/components/FormCol/index.vue";
import DeptSelect from "@/components/Business/Dept/DeptSelect.vue";
import BooleanTag from "@/components/BooleanTag/index.vue";
import {isEmpty} from "@/utils";
import {$prodOrder} from "@/views/yh/prodOrder/mixins";
import ProdOrderProgress from "@/views/yh/prodOrder/components/ProdOrderProgress.vue";

// 默认排序字段
const defaultSort = {
  prop: "createTime",
  order: "descending"
}

export default {
  name: "ProdOrder",
  mixins: [$showColumns, $prodOrder],
  dicts: ['prod_order_erp_document_status', 'prod_order_erp_status', 'prod_order_erp_req_src'],
  components: {ProdOrderProgress, BooleanTag, DeptSelect, FormCol},
  data() {
    return {
      span: 24,
      // 字段列表
      columns: [
        {key: 'id', visible: false, label: '生产订单ID', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'erpId', visible: false, label: 'ID', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'erpMtoNo', visible: true, label: '跟踪号', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100"},
        {key: 'erpBillNo', visible: true, label: '编号', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'erpStatus', visible: true, label: '状态', minWidth: null, sortable: true, overflow: false, align: 'center', width: "80"},
        {key: 'erpDocumentStatus', visible: false, label: '单据', minWidth: null, sortable: true, overflow: false, align: 'center', width: "80"},
        {key: 'erpDescription', visible: false, label: '主备注', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'materialNumber', visible: true, label: '物料', minWidth: null, sortable: false, overflow: false, align: 'center', width: null},
        {key: 'workShopName', visible: true, label: '车间', minWidth: null, sortable: true, overflow: false, align: 'center', width: "100"},
        {key: 'erpIsRework', visible: true, label: '返工', minWidth: null, sortable: true, overflow: false, align: 'center', width: "80"},
        {key: 'percentage', visible: true, label: '进度', minWidth: null, sortable: false, overflow: false, align: 'left', width: "120"},
        {key: 'erpRowId', visible: false, label: '行标识', minWidth: null, sortable: true, overflow: true, align: 'center', width: null},
        {key: 'erpMemoItem', visible: true, label: '备注', minWidth: null, sortable: true, overflow: true, align: 'center', width: null},
        {key: 'time', visible: true, label: '时间', minWidth: null, sortable: false, overflow: false, align: 'left', width: "170"},
        {key: 'erpReqSrc', visible: false, label: '来源', minWidth: null, sortable: true, overflow: false, align: 'center', width: "80"},
        {key: 'erpBaseUnitQty', visible: false, label: '基本', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'erpBaseNoStockInQty', visible: false, label: '基本未入库', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'baseUnitName', visible: false, label: '基本单位', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
      ],
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产订单表格数据
      prodOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        id: null,
        billNo: null,
        type: null,
        status: null,
        transferStatus: null,
        pickStatus: null,
        spec: null,
        deptId: null,
        unit: null,
        bizStatus: null,
        batchNo: null,
        releaseTime: null,
        sourceNo: null,
        demandBill: null,
        planTrackNo: null,
        productType: null,
        materialNo: null,
        erpStatusList: [],
        erpIsRework: null,
        erpBillNo: null,
        erpDocumentStatus: null,
        materialCategory: null,
        materialSize: null,
        materialSurface: null,
        materialCover: null,
        materialGraphics: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        billNo: [
          { required: true, message: "单据编号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleView(row) {
      this.$router.push(`/view/prodOrder/${row.id}`)
    },
    isEmpty,
    handleSync(query = {}) {
      this.$confirm('确定同步生产订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        syncProdOrder(query).then(res => {
          if (res.code === 200) {
            this.$message.success("同步成功");
          }
        })
      })
    },
    /** 当排序按钮被点击时触发 **/
    onSortChange(column) {
      if (column.order == null) {
        this.queryParams.orderByColumn = defaultSort.prop;
        this.queryParams.isAsc = defaultSort.order;
      } else {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
      }
      this.getList();
    },
    /** 查询生产订单列表 */
    getList() {
      this.loading = true;
      listProdOrder(this.queryParams).then(response => {
        this.prodOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        billNo: null,
        type: null,
        billDate: null,
        status: null,
        transferStatus: null,
        pickStatus: null,
        spec: null,
        deptId: null,
        unit: null,
        num: null,
        bizStatus: null,
        batchNo: null,
        remark: null,
        releaseTime: null,
        sourceNo: null,
        demandBill: null,
        auxProp: null,
        planTrackNo: null,
        productType: null,
        materialNo: null,
        quaStore: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProdOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改生产订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProdOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProdOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除生产订单编号为"' + ids + '"的数据项？').then(function() {
        return delProdOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('yh/prodOrder/export', this.queryParams, `生产订单_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
