<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="workorderType">
            <el-select v-model="queryParams.workorderType" clearable :placeholder="$t('请选择状态')" >
                <el-option v-for="dict in dict.type.mes_workorder_type" 
                :key="dict.value" 
                :label="dict.label"
                :value="dict.value">
                </el-option>
            </el-select>
        </el-form-item>
        <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="orderSerial">
            <el-input v-model="queryParams.orderSerial" :placeholder="$t('请输入')" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item :label="$t('排产次数')" prop="taskBatch">
            <el-input v-model="queryParams.taskBatch" :placeholder="$t('请输入')" clearable @keyup.enter.native="handleQuery" />
        </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="taskCode">
            <el-input v-model="queryParams.taskCode" :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="processName">
          <el-input v-model="queryParams.processName" >
            <el-button slot="append" @click="$refs.brSelectpro.showFlag = true" icon="el-icon-search"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('车间')" prop="workshopName">
          <el-input v-model="queryParams.workshopName" >
            <el-button slot="append" @click="$refs.workshopSelectRef.showFlag = true" icon="el-icon-search"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('common.workstation')" prop="workstationName">
          <el-input
            v-model="queryParams.workstationName"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="$refs['WorkstationSelect'].showFlag = true"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('common.workunit')" prop="workunitId">
          <el-input v-model="queryParams.workunitName">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="$refs['WorkunitSelect'].showFlag = true"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('报工人员')" prop="workunitId">
          <el-input v-model="queryParams.nickName">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="$refs.userSelect.showFlag = true"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('计划开始时间')" prop="scheduleStartDate">
          <el-date-picker
            v-model="queryParams.scheduleStartDate"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            range-separator="-"
            :start-placeholder="$t('common.start_date')"
            :end-placeholder="$t('common.end_date')"
            clearable>
          </el-date-picker>
        </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-row style="margin-bottom: 10px;">
            <el-button type="primary" size="mini" @click="handleExport">{{$t('导出')}}</el-button>
          </el-row>
          <el-table v-loading="loading" :max-height="tableHeight" :data="tbodys" >
            <el-table-column :label="item.label" align="center" :prop="item.value" :width="item.width" 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'" />
                <span v-else-if="['scheduleStartDate','scheduleEndDate','feedbackTime'].includes(item.value)">
                  {{ parseTime(scope.row[item.value], '{y}-{m}-{d} {h}:{i}:{s}') }}
                </span>
                <div v-else>{{ item.value === 'machineTime' ? scope.row[item.value] ? Number(scope.row[item.value]).toFixed(2) : scope.row[item.value] : 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="7">{{$t('统计方式')}}
              <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="3">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('查询')}}</el-button>
              <el-button type="primary" size="mini" @click="handleExport">{{$t('导出')}}</el-button>
            </el-col>
          </el-row>
          <el-table v-loading="loading" :max-height="tableHeight" :data="tbodys1">
            <el-table-column :label="item.label" align="center" :prop="item.value" v-for="(item, index) in theaders1" :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>{{ item.value === 'machineTime' ? scope.row[item.value] ? Number(scope.row[item.value]).toFixed(2) : scope.row[item.value] : 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"/>
      <workshopSelect ref="workshopSelectRef" showModal @onSelected="onworkshopSelect"/>
      <WorkuintSelect
        ref="WorkunitSelect"
        showModal
        @onSelected="onWorkunitSelect"
      />
      <WorkstationSelect
        ref="WorkstationSelect"
        showModal
        @onSelected="onWorkstationSelect"
      />
      <ProcessSelect
        ref="brSelectpro"
        showModal
        @onSelected="onBrandProcess"
      ></ProcessSelect>
      <UserSingleSelect ref="userSelect" showModal @onSelected="onUserSelected"></UserSingleSelect>
    </div>
  </template>
  
  <script>
import i18n from '../../../../i18n/index'
import dayjs from 'dayjs'

  import { getList, getListByProcess, getListByUser, getListByWorkshop, getListByWorkOrder, getListByWorkstation, getListByWorkunit } from "@/api/mes/proTable/statistAnaly";
  import ProcessSelect from "@/components/process/taskSelectSingle.vue";
  import ItemSelect from "@/components/itemSelect/single.vue";
  import workshopSelect from "@/components/workshopSelect/single.vue";
  import WorkuintSelect from "@/components/workunitSelect/single.vue";
  import WorkstationSelect from "@/components/workstationSelect/simpletableSingle.vue"
  import UserSingleSelect from "@/components/userSelect/single1.vue"
  
  export default {
    name: "ScheduleSetupRule",
    components: {UserSingleSelect,ProcessSelect, ItemSelect, workshopSelect, WorkuintSelect, WorkstationSelect},
    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: [],
        tbodys1: [],
        theaders1: [],
        // 弹出层标题
        title: "",
        statisisType: null,
        statisisList: [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,
          "customerProjectNo": null,
          "endDate": null,
          "orderCode": null,
          "orderSerial": null,
          "taskBatch": null,
          scheduleStartDate: null,
          "processName": null,
          "processCode": null,
          "processId": null,
          "productCode": null,
          "productId": null,
          "productName": null,
          "startDate": null,
          "taskCode": null,
          "userName": null,
          "nickName": null,
          "workorderCode": null,
          "workorderType": null,
          "workshopId": null,
          "workshopName": null,
          "workstationId": null,
          "workstationName": null,
          "workunitId": null,
          "workunitName": null
        },
        // 表单参数
        form: {},
      };
    },
    mounted(){
      this.$nextTick(()=>{
        this._resizeHandler()
      })
      this._resizeHandler = () => {
        const arr = document.getElementsByClassName('el-form')
        const height = arr[0].offsetHeight
        const arr1 = document.getElementsByClassName('app-main')
        const height1 = arr1[0].offsetHeight
        console.log('this.tabIndex', this.tabIndex)
        this.tableHeight = height1 - height - (this.tabIndex ? 200 : 170)
      }
      window.addEventListener('resize', this._resizeHandler)
    },
    beforeDestroy() {
      window.removeEventListener('resize', this._resizeHandler)
    },
    created() {
      this.getList();
    },
    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: '240px'},
              {label: i18n.t('工序任务'), value: 'taskCode', width: '120px'},
              {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: 'stdWorkingTime', width: '80px'},
              {label: i18n.t('实际工时'), value: 'machineTime', width: '80px'},
              {label: i18n.t('排产次数'), value: 'taskBatch', width: '80px'},
              {label: i18n.t('订单序号'), value: 'orderSerial', width: '80px'},
              {label: i18n.t('计划开始时间'), value: 'scheduleStartDate', width: '160px'},
              {label: i18n.t('计划完成时间'), value: 'scheduleEndDate', width: '160px'},
              {label: i18n.t('报工时间'), value: 'feedbackTime', width: '100px'}
            ]
            this.handleQuery()
          }
        },
        immediate: true
      }
    },
    methods: {
      onUserSelected(row){
        if (row != undefined) {
          console.log('rrr', row)
          this.queryParams.nickName = row.nickName;
        }
      },
      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
        this.$nextTick(() => {
          this._resizeHandler()
        })
      },
      onItemSelect(row) {
        if (row != undefined) {
          this.queryParams.productName = row.itemName;
        }
      },
      buildQueryParams() {
        const params = { ...this.queryParams }
        if (this.daterangePurchaseDate && this.daterangePurchaseDate.length > 0) {
          params.startDate = this.daterangePurchaseDate[0]
          params.endDate = this.daterangePurchaseDate[1]
        } else {
          params.startDate = null
          params.endDate = null
        }
        if (params.scheduleStartDate && params.scheduleStartDate.length > 0) {
          params.scheduleStartDateFrom = params.scheduleStartDate[0]
          params.scheduleStartDateTo = params.scheduleStartDate[1]
        } else {
          params.scheduleStartDateFrom = null
          params.scheduleStartDateTo = null
        }
        delete params.scheduleStartDate
        return params
      },
      /** 查询排产换型对照信息列表 */
      getList() {
        this.loading = true;
        const query = this.buildQueryParams()
        let api = getList
        if (Number(this.tabIndex) === 1) {
          if(this.statisisType === i18n.t('工单')){
            api = getListByWorkOrder
            this.theaders1 = [
              {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('车间')){
            this.theaders1 = [
              {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.theaders1 = [
              {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.theaders1 = [
              {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.theaders1 = [
              {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.theaders1 = [
              {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(query).then(response => {
          if (Number(this.tabIndex) === 1) {
            this.tbodys1 = response.rows
          }
          else {
            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(){
        let apiName = ''
        if (Number(this.tabIndex) === 0) {
          apiName = 'report/pro/feedback/getList/export'
        } else if(this.statisisType === i18n.t('车间')){
          apiName = 'report/pro/feedback/getListByWorkshop/export'
        } else if(this.statisisType === i18n.t('工作中心')){
          apiName = 'report/pro/feedback/getListByWorkstation/export'
        } else if(this.statisisType === i18n.t('工作单元')){
          apiName = 'report/pro/feedback/getListByWorkunit/export'
        } else if(this.statisisType === i18n.t('工序')){
          apiName = 'report/pro/feedback/getListByProcess/export'
        } else if(this.statisisType === i18n.t('人员')){
          apiName = 'report/pro/feedback/getListByUser/export'
        } else if(this.statisisType === i18n.t('工单')) {
          apiName = 'report/pro/feedback/getListByWorkOrder/export'
        }
        this.download(
          apiName,
          this.buildQueryParams(),
          `statistAnaly_${new Date().getTime()}.xlsx`
        );
      }
    }
  };
  </script>
  