<template>
  <div class="app-container">
    <el-form :model="queryParams" @submit.native.prevent ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item :label="$t('项目号')" prop="customerProjectNo">
          <el-input v-model="queryParams.customerProjectNo" :placeholder="$t('请输入项目号')"  />
      </el-form-item>
      <el-form-item :label="$t('订单号')" prop="orderCode">
          <el-input v-model="queryParams.orderCode" :placeholder="$t('请输入订单号')"  />
      </el-form-item>
      <el-form-item :label="$t('生产工单')" prop="workorderCode">
          <el-input v-model="queryParams.workorderCode" :placeholder="$t('请输入生产工单')"  />
      </el-form-item>
      <el-form-item :label="$t('产品编码')" prop="productCode">
          <el-input v-model="queryParams.productCode" :placeholder="$t('请输入产品编码')"  />
      </el-form-item>
      <el-form-item :label="$t('产品名称')" prop="productName">
        <el-input v-model="queryParams.productName"  >
          <el-button slot="append" icon="el-icon-search" @click="$refs['ItemSelectRef'].showFlag = true" ></el-button>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('不合格原因')" prop="abnormalReason">
        <el-input v-model="queryParams.abnormalReason" >
          <el-button slot="append" @click="$refs.reasonSelect.showFlag = true" icon="el-icon-search"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('不合格时间')">
        <el-date-picker v-model="daterangePurchaseDate" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
          :start-placeholder="$t('common.start_date')" :end-placeholder="$t('common.end_date')"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('搜索')}}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t('重置')}}</el-button>
      </el-form-item>
    </el-form>

    <el-tabs type="border-card" @tab-click="tabClick">
      <el-tab-pane :label="$t('明细')">
        <el-table v-loading="loading" :data="tbodys" :max-height="tableHeight">
            <el-table-column :label="item.label" :width="item.width" align="center" :prop="item.value" v-for="(item, index) in theaders" :key="index">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.mes_workorder_type" :value="scope.row.workorderType"  v-if="item.value==='workorderType'" />
                <div v-else>{{ scope.row[item.value] }}</div>
              </template>
            </el-table-column>
        </el-table>
    
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>
      <el-tab-pane :label="$t('统计')">
        <el-row align="center" style="line-height: 40px;">
          <el-col :span="1">{{$t('统计方式')}}</el-col>
          <el-col :span="4">
            <el-select v-model="statisisType" clearable :placeholder="$t('请选择统计方式')">
              <el-option v-for="item in statisisList" 
              :key="item" 
              :label="item"
              :value="item">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="1">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('查询')}}</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="tbodys" :max-height="tableHeight">
          <el-table-column :label="item.label" align="center" :prop="item.value" v-for="(item, index) in theaders" :key="index">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.mes_workorder_type" :value="scope.row.workorderType"  v-if="item.value==='workorderType'" />
              <div v-else>{{ scope.row[item.value] }}</div>
            </template>
          </el-table-column>
        </el-table>
    
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>
    </el-tabs>
    
    <ItemSelect ref="ItemSelectRef" @onSelected="onItemSelect"/>
    <reasonSelect ref="reasonSelect" showModal @onSelected="onReasonSelected"></reasonSelect>
  </div>
</template>

<script>
import i18n from '../../../../i18n/index'

import { getList, getListByProcess, getListByUser, getListByWorkshop, getListByDefect, getListByWorkOrder, getListByWorkstation, getListByWorkunit } from "@/api/mes/proTable/statistAnaly";
import ItemSelect from "@/components/itemSelect/single.vue";
import reasonSelect from "@/components/reasonSelect/single.vue"
import dayjs from 'dayjs'

export default {
  name: "ScheduleSetupRule",
  components: {ItemSelect,reasonSelect},
  dicts: [
  "mes_workorder_type",
],
  data() {
    return {
      showQueryLPN: false,
      // 遮罩层
      loading: true,
      selectedRows: [],
      tabIndex: 0,
      // 选中数组
      ids: [],
      //dta列表
      dtaOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排产换型对照信息表格数据
      tbodys: [],
      theaders: [],
      // 弹出层标题
      title: "",
      statisisType: null,
      statisisList: [i18n.t('不合格原因'), i18n.t('工单'), i18n.t('车间'), i18n.t('工作中心'), i18n.t('工作单元'), i18n.t('工序'), i18n.t('人员')],
      // 是否显示弹出层
      open: false,
      tableHeight: 0,
      daterangePurchaseDate: [dayjs().startOf('month').format('YYYY-MM-DD'), dayjs().endOf('month').format('YYYY-MM-DD')],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        defectStatus: true,
        "customerProjectNo": null,
        "endDate": null,
        "orderCode": null,
        "processName": null,
        "processCode": null,
        "processId": null,
        "productCode": null,
        "productId": null,
        "productName": null,
        "startDate": null,
        "taskCode": null,
        "abnormalReason": null,
        "workorderCode": null,
        "workorderType": null,
        "workshopId": null,
        "workshopName": null,
        "workstationId": null,
        "workstationName": null,
        "workunitId": null,
        "workunitName": null
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    this.getList();
  },
  mounted(){
    this.$nextTick(()=>{
      this._resizeHandler()
    })
    this._resizeHandler = () => {
      this.tableHeight = window.innerHeight - 350
    }
    window.addEventListener('resize', this._resizeHandler)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this._resizeHandler)
  },
  watch: {
    tabIndex: {
      handler(val){
        if(Number(val) === 0) {
          this.theaders = [
            {label: i18n.t('工单类型'), value: 'workorderType', width: '80px'},
            {label: i18n.t('项目号'), value: 'customerProjectNo', width: '80px'},
            {label: i18n.t('订单号'), value: 'orderCode', width: '80px'},
            {label: i18n.t('生产工单'), value: 'workorderCode', width: '140px'},
            {label: i18n.t('产品编码'), value: 'productCode', width: '120px'},
            {label: i18n.t('产品名称'), value: 'productName', width: '120px'},
            {label: i18n.t('工序任务'), value: 'taskCode', width: '240px'},
            {label: i18n.t('工序名称'), value: 'processName', width: '80px'},
            {label: i18n.t('工作中心编码'), value: 'workstationCode', width: '100px'},
            {label: i18n.t('工作中心名称'), value: 'workstationName', width: '140px'},
            {label: i18n.t('工作单元编码'), value: 'workunitCode', width: '100px'},
            {label: i18n.t('工作单元名称'), value: 'workunitName', width: '280px'},
            {label: i18n.t('报工人员编码'), value: 'userName', width: '140px'},
            {label: i18n.t('报工人员名称'), value: 'nickName', width: '140px'},
            {label: i18n.t('派工数量'), value: 'quantity', width: '80px'},
            {label: i18n.t('报工数量'), value: 'quantityFeedback', width: '80px'},
            {label: i18n.t('合格数量'), value: 'quantityQualify', width: '80px'},
            {label: i18n.t('不合格数量'), value: 'quantityUnqualify', width: '90px'},
            {label: i18n.t('不合格原因'), value: 'abnormalReason', width: '90px'},
            {label: i18n.t('不合格时间'), value: 'feedbackTime', width: '100px'}
          ]
          this.handleQuery()
        } else {
          this.statisisType = null
          this.theaders = []
          this.total = 0
        }
      },
      immediate: true
    }
  },
  methods: {
    onReasonSelected(row){
      if (row != undefined) {
        this.queryParams.abnormalReason = row.abnormalReason;
      }
    },
    onWorkstationSelect(row) {
      if (row != undefined) {
        this.queryParams.workstationName = row.workstationName;
      }
    },
    onWorkunitSelect(row){
      if (row != undefined) {
        this.queryParams.workunitName = row.workunitName;
      }
    },
    onworkshopSelect(row){
      if (row != undefined) {
        this.queryParams.workshopName = row.workshopName;
      }
    },
    tabClick(val){
      console.log('this.tabIndex', this.tabIndex, val)
      this.tabIndex = val.index
    },
    onItemSelect(row) {
      if (row != undefined) {
        this.queryParams.productName = row.itemName;
      }
    },
    /** 查询排产换型对照信息列表 */
    getList() {
      this.loading = true;
      this.queryParams['defectStatus'] = true
      if (this.daterangePurchaseDate && this.daterangePurchaseDate.length > 0) {
        this.queryParams['startDate'] = this.daterangePurchaseDate[0]
        this.queryParams['endDate'] = this.daterangePurchaseDate[1]
      } else {
          this.queryParams['startDate'] = null
          this.queryParams['endDate'] = null
        }
      let api = getList
      if (Number(this.tabIndex) === 1) {
        if(this.statisisType === i18n.t('工单')){
          api = getListByWorkOrder
          this.theaders = [
            {label: i18n.t('工单编码'), value: 'workorderCode'},
            {label: i18n.t('工单名称'), value: 'workorderName'},
            {label: i18n.t('报工数量'), value: 'quantityFeedback'},
            {label: i18n.t('合格数量'), value: 'quantityQualify'},
            {label: i18n.t('不合格数量'), value: 'quantityUnqualify'},
            {label: i18n.t('合格率'), value: 'qualificationRate'}
          ]
          
        } else if(this.statisisType === i18n.t('不合格原因')){
          api = getListByDefect
          this.theaders = [
            {label: i18n.t('不合格原因'), value: 'abnormalReason'},
            {label: i18n.t('不合格备注'), value: 'abnormalRemark'},
            {label: i18n.t('报工数量'), value: 'quantityFeedback'},
            {label: i18n.t('合格数量'), value: 'quantityQualify'},
            {label: i18n.t('不合格数量'), value: 'quantityUnqualify'},
            {label: i18n.t('合格率'), value: 'qualificationRate'}
          ]
        } else if(this.statisisType === i18n.t('车间')){
          this.theaders = [
            {label: i18n.t('车间编号'), value: 'workshopCode'},
            {label: i18n.t('车间名称'), value: 'workshopName'},
            {label: i18n.t('报工数量'), value: 'quantityFeedback'},
            {label: i18n.t('合格数量'), value: 'quantityQualify'},
            {label: i18n.t('不合格数量'), value: 'quantityUnqualify'},
            {label: i18n.t('合格率'), value: 'qualificationRate'}
          ]
          api = getListByWorkshop
        } else if(this.statisisType === i18n.t('工作中心')){
          this.theaders = [
            {label: i18n.t('工作中心编号'), value: 'workstationCode'},
            {label: i18n.t('工作中心名称'), value: 'workstationName'},
            {label: i18n.t('报工数量'), value: 'quantityFeedback'},
            {label: i18n.t('合格数量'), value: 'quantityQualify'},
            {label: i18n.t('不合格数量'), value: 'quantityUnqualify'},
            {label: i18n.t('合格率'), value: 'qualificationRate'}
          ]
          api = getListByWorkstation
        } else if(this.statisisType === i18n.t('工作单元')){
          this.theaders = [
            {label: i18n.t('工作单元编码'), value: 'workunitCode'},
            {label: i18n.t('工作单元名称'), value: 'workunitName'},
            {label: i18n.t('报工数量'), value: 'quantityFeedback'},
            {label: i18n.t('合格数量'), value: 'quantityQualify'},
            {label: i18n.t('不合格数量'), value: 'quantityUnqualify'},
            {label: i18n.t('合格率'), value: 'qualificationRate'}
          ]
          api = getListByWorkunit
        } else if(this.statisisType === i18n.t('工序')){
          this.theaders = [
            {label: i18n.t('工序编码'), value: 'processCode'},
            {label: i18n.t('工序名称'), value: 'processName'},
            {label: i18n.t('报工数量'), value: 'quantityFeedback'},
            {label: i18n.t('合格数量'), value: 'quantityQualify'},
            {label: i18n.t('不合格数量'), value: 'quantityUnqualify'},
            {label: i18n.t('合格率'), value: 'qualificationRate'}
          ]
          api = getListByProcess
        } else if(this.statisisType === i18n.t('人员')){
          this.theaders = [
            {label: i18n.t('报工人员编码'), value: 'userName'},
            {label: i18n.t('报工人员名称'), value: 'nickName'},
            {label: i18n.t('报工数量'), value: 'quantityFeedback'},
            {label: i18n.t('合格数量'), value: 'quantityQualify'},
            {label: i18n.t('不合格数量'), value: 'quantityUnqualify'},
            {label: i18n.t('合格率'), value: 'qualificationRate'}
          ]
          api = getListByUser
        }
      }
      api(this.queryParams).then(response => {
        this.tbodys = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (Number(this.tabIndex) === 1 && !this.statisisType) this.$modal.msgWarnning(this.$t(i18n.t('请选择统计方式')));
      this.queryParams.pageNum = 1;
      this.getList();
    },
    onBrandSelected(row){
     if (Object.values(row).length > 0) {
        this.queryParams.itemTypeId = row.itemTypeId;
        this.queryParams.itemTypeName = row.itemTypeName;
      }
    },
    onBrandProcess(row){
     if (Object.values(row).length > 0) {
        this.queryParams.processName = row.processName;
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.ids = selection.map(item => item.ruleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      const row = this.selectedRows[0]
      this.download('pro/serial/lpn/record/export', {
        salesVoucher: row.salesVoucher,
        salesVoucherItem: row.salesVoucherItem,
      }, `dta_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
