<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('月份')">
        <el-date-picker v-model="queryParams.dateWeekly" type="month" value-format="yyyy-MM"></el-date-picker>
      </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-row>
        <el-col>
          <el-form-item :label="$t('统计方式')" prop="statisisType">
            <el-select v-model="statisisType" :placeholder="$t('请选择统计方式')">
              <el-option v-for="item in statisisList" 
              :key="item" 
              :label="item"
              :value="item">
              </el-option>
            </el-select>
          </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-col>
      </el-row>
      
      
    </el-form>

    <div class="table-box" style="width: 100%">
        <el-table v-loading="loading" :data="tbodys" show-summary class='tableHei' :max-height="tableHeight" :summary-method="getSummaries">
          <el-table-column :label="item.label" align="center" :prop="item.value" v-for="(item, index) in theaders.slice(0, 2)" :key="index + 'key'" fixed="left" width="150" />
          <el-table-column :label="item.label" align="center" :prop="item.value" v-for="(item, index) in theaders.slice(2)" :key="index" width="150">
            <el-table-column prop="报工数量" :label="$t('报工数量')">
              <template slot-scope="scope">
                {{scope.row[item.value]['报工数量']}}
              </template>
            </el-table-column>
            <el-table-column prop="合格数量" :label="$t('合格数量')">
              <template slot-scope="scope">
                {{scope.row[item.value]['合格数量']}}
              </template>
            </el-table-column>
            <el-table-column prop="不合格数量" :label="$t('不合格数量')" width="100">
              <template slot-scope="scope">
                {{scope.row[item.value]['不合格数量']}}
              </template>
            </el-table-column>
            <el-table-column prop="合格率" :label="$t('合格率')">
              <template slot-scope="scope">
                {{scope.row[item.value]['合格率'] ? (scope.row[item.value]['合格率'] + '%') : ''}}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
    
    </div>
    
    <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 { getDatas, getListByProcess, getListByUser, getListByWorkshop, getListByWorkOrder, getListByWorkstation, getListByWorkunit } from "@/api/mes/proTable/weekStatist";
import ProcessSelect from "@/components/process/taskSelectSingle.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"
import dayjs from 'dayjs'
export default {
  name: "ScheduleSetupRule",
  components: {UserSingleSelect,ProcessSelect, 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,
      // 排产换型对照信息表格数据
      tbodys: [],
      theaders: [],
      // 弹出层标题
      title: "",
      statisisType: i18n.t('工序'),
      statisisList: [i18n.t('车间'), i18n.t('工作中心'), i18n.t('工作单元'), i18n.t('工序'), i18n.t('人员')],
      // 是否显示弹出层
      open: false,
      tableHeight: 0,
      daterangePurchaseDate: [],
      tableSum: {},
      // 查询参数
      queryParams: {
        "customerProjectNo": null,
        "orderCode": null,
        "processName": null,
        "processCode": null,
        "processId": null,
        "productCode": null,
        "productId": null,
        "productName": null,
        "dateWeekly": dayjs().startOf('month').format('YYYY-MM'),
        "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 = () => {
      this.tableHeight = window.innerHeight - 320
    }
    window.addEventListener('resize', this._resizeHandler)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this._resizeHandler)
  },
  created() {
    this.getList();
  },
  watch: {
  },
  methods: {
    getSummaries(param){
      const { columns, data } = param
      const sums = []
      if(!this.tableSum) returnreturn [""]
      const keys = Object.keys(this.tableSum).sort()
      if(!keys || keys.length === 0) return [""]
      const itemkeys = Object.keys(this.tableSum[keys[0]])

      columns.forEach((column, index) => {
        if (index === 0 || index === 1) {
          sums[index] = ''
          return
        } 
        const num4 = index - 2
        if (num4 % 4 === 0){

          const keyindex = num4 / 4
          itemkeys.forEach(v => {
            if (v.includes('报工数量')) {
              sums[index] = this.tableSum[keys[keyindex]][v] || this.tableSum[keys[keyindex]]['报工数量']
            } else if (v.includes('不合格数量')) {
              sums[index + 2] = this.tableSum[keys[keyindex]][v] || this.tableSum[keys[keyindex]]['不合格数量']
            } else if (v.includes('合格数量')) {
              sums[index + 1] = this.tableSum[keys[keyindex]][v] || this.tableSum[keys[keyindex]]['合格数量']
            } else if (v.includes('合格率')) {
              sums[index + 3] = this.tableSum[keys[keyindex]][v] || this.tableSum[keys[keyindex]]['合格率']
              sums[index + 3] = sums[index + 3]  ? (sums[index + 3] + '%') : ''
            }
          })
        }
      })
      return sums
    },
    onUserSelected(row){
      if (row != undefined) {
        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;
      }
    },
    onItemSelect(row) {
      if (row != undefined) {
        this.queryParams.productName = row.itemName;
      }
    },
    /** 查询排产换型对照信息列表 */
    async getList() {
      this.loading = true;
      await getDatas(this.queryParams).then(res1 => {
        if (res1.data) {
          const obj = {
            1: i18n.t('第一周'),
            2: i18n.t('第二周'),
            3: i18n.t('第三周'),
            4: i18n.t('第四周'),
            5: i18n.t('第五周'),
            6: i18n.t('第六周'),
            7: i18n.t('第七周'),
          }
          this.theaders = res1.data.map(v => ({label: obj[v], value: v}))
          this.theaders.push({label: i18n.t('合计'), value: '合计'})
        }
      })
      let api = getListByWorkOrder
      if(this.statisisType === i18n.t('车间')){
        this.theaders.unshift(...[
          {label: i18n.t('车间编号'), value: '车间编码'},
          {label: i18n.t('车间名称'), value: '车间名称'}
        ])
        api = getListByWorkshop
      } else if(this.statisisType === i18n.t('工作中心')){
        this.theaders.unshift(...[
          {label: i18n.t('工作中心编号'), value: '工作中心编码'},
          {label: i18n.t('工作中心名称'), value: '工作中心名称'}
        ])
        api = getListByWorkstation
      } else if(this.statisisType === i18n.t('工作单元')){
        this.theaders.unshift(...[
          {label: i18n.t('工作单元编码'), value: '工作单元编码'},
          {label: i18n.t('工作单元名称'), value: '工作单元名称'}
        ])
        api = getListByWorkunit
      } else if(this.statisisType === i18n.t('工序')){
        this.theaders.unshift({label: i18n.t('工序名称'), value: '工序名称'})
        this.theaders.unshift({label: i18n.t('工序编码'), value: '工序编码'})
        api = getListByProcess
      } else if(this.statisisType === i18n.t('人员')){
        this.theaders.unshift(...[
          {label: i18n.t('报工人员编码'), value: '报工人员编码'},
          {label: i18n.t('报工人员名称'), value: '报工人员名称'}
        ])
        api = getListByUser
      }
      const sumObj = {
        '报工数量': 0,
        '不合格数量': 0,
        '合格数量': 0,
        '合格率': 0,
      }
      api(this.queryParams).then(response => {
        response.data.forEach(element => {
          element['合计'] = {}
          Object.keys(element).forEach(key => {
            if (key.includes('报工数量')) {
              element['合计']['报工数量'] = element[key]
              sumObj['报工数量'] += (Number(element[key]) || 0)
            } else if (key.includes('不合格数量')) {
              element['合计']['不合格数量'] = element[key]
              sumObj['不合格数量'] += (Number(element[key]) || 0)
            } else if (key.includes('合格数量')) {
              element['合计']['合格数量'] = element[key]
              sumObj['合格数量'] += (Number(element[key]) || 0)
            } else if (key.includes('合格率')) {
              element['合计']['合格率'] = element[key]
            }
          })
        });
        sumObj['合格率'] = ((sumObj['合格数量'] / sumObj['报工数量']) * 100).toFixed(2)
        this.tbodys = response.data.slice(0, response.data.length - 1);
        response.data[response.data.length - 1]['合计'] = sumObj
        this.tableSum = response.data[response.data.length - 1]

        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      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
    }
  }
};
</script>
<style lang="scss" scoped>
.tableHei ::v-deep th {
  padding: 0 !important;
  height: 25px;
  line-height: 15px;
  text-align: center;
}
.tableHei ::v-deep td {
  padding: 0 !important;
  height: 35px;
  line-height: 30px;
  text-align: center;
}
.table-box {
  ::v-deep  .el-table__body-wrapper {
  z-index: 2
  }
}

</style>