<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="'工序'" 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="'车间'" 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="'工作中心'" 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="'工作单元'" 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="'异常时间'">
          <el-date-picker v-model="daterangePurchaseDate" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
            :start-placeholder="'开始日期'" :end-placeholder="'结束日期'"></el-date-picker>
        </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-tabs type="border-card" @tab-click="tabClick">
        <el-tab-pane :label="'明细'">
          <!-- <el-row style="margin-bottom: 10px;">
            <el-button type="primary" size="mini" @click="handleExport">{{'导出'}}</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'" />
                <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="'统计'">
          <el-row align="center"  style="line-height: 40px;">
            <el-col :span="7">{{'统计方式'}}
              <el-select v-model="statisisType" clearable :placeholder="'请选择统计方式'">
                <el-option v-for="item in statisisList" 
                :key="item" 
                :label="item"
                :value="item">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="7">{{'统计颗粒度'}}
              <el-select v-model="groupKey" clearable :placeholder="'请选择统计颗粒度'">
                <el-option v-for="item in groupbyList" 
                :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" style="margin-left: 10px;">{{'查询'}}</el-button>
              <!-- <el-button type="primary" size="mini" @click="handleExport">{{'导出'}}</el-button> -->
            </el-col>
          </el-row>
          <el-table v-loading="loading" :max-height="tableHeight" :data="tbodys1" @sort-change="handleSortChange">
            <el-table-column :label="item.label" align="center" :prop="item.value" v-for="(item, index) in theaders1" :key="index" :sortable="item.sort? 'custom':false">
              <!-- <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>
    </div>
  </template>
  
  <script>
import dayjs from 'dayjs'

  import { getList, getListByProcess, getResponsibilityRanking, getLossRanking, getReasonRanking } from "@/api/mes/proTable/timeDelayStatic";
  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 FactorySelect from "@/components/FactorySelect/index.vue";
  
  export default {
    name: "ScheduleSetupRule",
    components: {FactorySelect,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,
        groupKey: null,
        statisisList: ['主要异常原因分析', '损失工时排行', '责任部门排行'],
        groupbyList: ['工作单元', '工作中心', '车间', '部门', '工厂'],
        // 是否显示弹出层
        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,
          "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,
          factoryCode: null,
          factoryName: 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
        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: '异常原因', value: 'abnormalReason'},
              {label: '损失单元', value: 'workunitName'},
              {label: '责任部门', value: 'dept', width: '120px'},
              {label: '异常发起时间', value: 'exceptionTime', width: '240px'},
              {label: '非排班时长', value: 'restTimeS', width: '120px'},
              {label: '异常后任务开工时间', value: 'recoveryTime'},
              {label: '当前工序雇员数', value: 'empCount'},
              {label: '延误工时', value: 'faildTimeM', width: '140px'}
            ]
            this.handleQuery()
          }
        },
        immediate: true
      }
    },
    methods: {
      handleSortChange(column) {
        const p = {}
        if (column.order === 'ascending') {
          p['ascSort'] = [column.prop]
        } else if (column.order === 'descending'){
          p['descSort'] = [column.prop]
        }
        this.getList(p);
      },
      onFactorySelect(row) {
        if (row != undefined && row != null) {
          this.queryParams.factoryCode = row.factoryCode;
          this.queryParams.factoryName = row.factoryName;
        }
      },
      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;
        }
      },
      /** 查询排产换型对照信息列表 */
      getList(p) {
        this.loading = true;
        let param = JSON.parse(JSON.stringify(this.queryParams))
        if (p) {
          param = {...param, ...p}
        }
        if (this.daterangePurchaseDate && this.daterangePurchaseDate.length > 0) {
          param['feedTime'] = {
            startDate:this.daterangePurchaseDate[0],
            endDate:this.daterangePurchaseDate[1]
          }
        } else {
          param['feedTime'] = null
        }
        let api = getList
        if (Number(this.tabIndex) === 1) {
          if(this.statisisType === '主要异常原因分析'){
            api = getReasonRanking
            this.theaders1 = [
              {label: '异常原因（分组）', value: 'expcetionReason'},
              {label: '时间范围', value: 'timeRange'},
              {label: '异常次数', value: 'expCount', sort: true},
              {label: '合计延误工时', value: 'workTimeSumM', sort: true}
            ]
            console.log('api1111', api, this.statisisType)
          } else if(this.statisisType === '损失工时排行'){
            this.theaders1 = [
              {label: '工作单元', value: 'workunitName'},
              {label: '工作中心', value: 'workstationName'},
              {label: '车间', value: 'workshopName'},
              {label: '部门', value: 'deptName'},
              {label: '工厂', value: 'factoryName'},
              {label: '时间范围', value: 'timeRange'},
              {label: '合计延误工时', value: 'lossTimeSumM', sort: true}
            ]
            api = getLossRanking
          } else if(this.statisisType === '责任部门排行'){
            this.theaders1 = [
              {label: '责任部门', value: 'rtDept'},
              {label: '时间范围', value: 'timeRange'},
              {label: '合计责任工时', value: 'rtTimeSumM', sort: true}
            ]
            api = getResponsibilityRanking
          }
          param['groupKey'] = [this.groupKey]
        }
        
        api(param).then(response => {
          console.log('response', response)
          if (Number(this.tabIndex) === 1) {
            this.tbodys1 = response.rows
          }
          else {
            this.tbodys = response.rows
          }
          this.total = response.total;
        }).finally(() => {
          this.loading = false;
        });;
      },
      /** 搜索按钮操作 */
      handleQuery() {
        if (Number(this.tabIndex) === 1 && !this.statisisType) this.$message.warning('请选择统计方式');
        if (Number(this.tabIndex) === 1 && !this.groupKey) this.$message.warning('请选择统计颗粒度');
        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 === '损失工时排行'){
          apiName = 'report/pro/feedback/getLossRanking/export'
        } else if(this.statisisType === '工作中心'){
          apiName = 'report/pro/feedback/getListByWorkstation/export'
        } else if(this.statisisType === '工作单元'){
          apiName = 'report/pro/feedback/getListByWorkunit/export'
        } else if(this.statisisType === '工序'){
          apiName = 'report/pro/feedback/getListByProcess/export'
        } else if(this.statisisType === '责任部门排行'){
          apiName = 'report/pro/feedback/getResponsibilityRanking/export'
        } else if(this.statisisType === '主要异常原因分析') {
          apiName = 'report/pro/feedback/getReasonRanking/export'
        }
        this.download(
          apiName,
          {
            ...this.queryParams,
          },
          `statistAnaly_${new Date().getTime()}.xlsx`
        );
      }
    }
  };
  </script>
  