<template>
  <div class="mys-container 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="lineName">
          <el-input v-model="queryParams.lineName" :placeholder="$t('请输入')"  />
      </el-form-item>
      <el-form-item :label="$t('排产次数')" prop="taskBatch">
          <el-input v-model="queryParams.taskBatch" :placeholder="$t('请输入')"  />
      </el-form-item>
      <el-form-item :label="$t('排产日期')" label-width="100px" prop="scheduleDate">
        <el-date-picker
          v-model="queryParams.scheduleDate"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          :range-separator="$t('至')"
          :start-placeholder="$t('common.start_date')"
          :end-placeholder="$t('common.end_date')"
          clearable>
        </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('订单序号')" prop="orderSerial">
          <el-input v-model="queryParams.orderSerial" :placeholder="$t('请输入')"  />
      </el-form-item>
      <el-form-item :label="$t('工单状态')" prop="status">
        <el-select v-model="queryParams.workOrderStatus" clearable multiple>
          <el-option v-for="dict in dict.type.mes_workorder_status" :key="dict.value" :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
      </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>
        <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-row ref="toolbarRow" style="margin-bottom: 10px;">
      <el-button type="primary" size="mini" @click="handleExport">{{$t('导出')}}</el-button>
    </el-row>
    <el-table v-loading="loading" :data="tbodys" @row-click="mainTableClick" :height="tableHeight" :row-class-name="tableRowClassName">
        <el-table-column :label="$t('项目号')" align="center" prop="customerProjectNo"></el-table-column>
        <el-table-column :label="$t('订单号')" align="center" prop="orderCode"></el-table-column>
        <el-table-column :label="$t('生产工单')" align="center" prop="workorderCode"></el-table-column>
        <el-table-column :label="$t('排产次数')" align="center" prop="taskBatch"></el-table-column>
        <el-table-column :label="$t('排产日期')" align="center" prop="scheduleDate" width="170">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.scheduleDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('订单序号')" align="center" prop="orderSerial"></el-table-column>
        <el-table-column :label="$t('所属产线')" align="center" prop="lineName"></el-table-column>
        <el-table-column :label="$t('工单状态')" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_workorder_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('首道未完成工序')" align="center" prop="firstUnfinishedProcessName" width="140" show-overflow-tooltip />
        <el-table-column :label="$t('工单类型')" align="center" prop="workorderType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_workorder_type" :value="scope.row.workorderType" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('产品编码')" align="center" prop="productCode"></el-table-column>
        <el-table-column :label="$t('产品名称')" align="center" prop="productName"></el-table-column>
        <el-table-column :label="$t('计划数量')" align="center" prop="quantity"></el-table-column>
        <el-table-column :label="$t('完工数量')" align="center" prop="quantityProduced"></el-table-column>
        <el-table-column :label="$t('在制进度')" align="center" prop="customerProjectNo">
          <template slot-scope="scope">
            <el-progress :text-inside="true" :stroke-width="26" :percentage="scope.row.quantityMu" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('需求时间')" align="center" prop="requestDate"></el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <div class="second-box" v-if="isShowSecond">
      <el-table v-loading="loadingLeft" :data="tbodysLeft" border @row-click="secondTableClick" :height="tableHeightSecond" :row-class-name="tableRowClassName1">
        <el-table-column :label="$t('状态')" align="center" prop="status"></el-table-column>
        <el-table-column :label="$t('工序名称')" align="center" prop="processName"></el-table-column>
        <el-table-column :label="$t('派工数量')" align="center" prop="quantity"></el-table-column>
        <el-table-column :label="$t('报工数量')" align="center" prop="quantityProduced">
        </el-table-column>
        <el-table-column :label="$t('合格数量')" align="center" prop="quantityQualify"></el-table-column>
        <el-table-column :label="$t('不合格数量')" align="center" prop="quantityUnqualify"></el-table-column>
        <el-table-column :label="$t('合格率')" align="center" prop="passRate">
          <template slot-scope="scope">
            {{scope.row.passRate ? `${scope.row.passRate}%` : ''}}
          </template>
        </el-table-column>
      </el-table>
      <el-table v-loading="loadingRight" :data="tbodysRight" border :height="tableHeightSecond" style="margin-left: 15px">
        <el-table-column :label="$t('排产次数')" align="center" prop="taskBatch" >
          <template slot-scope="scope">
            {{scope.row.taskBatch.split('-').length > 1 ? scope.row.taskBatch.split('-')[scope.row.taskBatch.split('-').length - 1]: ''}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('报工人员')" align="center" prop="nickName"></el-table-column>
        <el-table-column :label="$t('报工数量')" align="center" prop="quantityFeedback"></el-table-column>
        <el-table-column :label="$t('合格数量')" align="center" prop="quantityQualify"></el-table-column>
        <el-table-column :label="$t('不合格数量')" align="center" prop="quantityUnqualify">
        </el-table-column>
        <el-table-column :label="$t('标准工时')" align="center" prop="stdWorkingTime"></el-table-column>
        <el-table-column :label="$t('实际工时')" align="center" prop="machineTime">
          <template slot-scope="scope">
            {{scope.row['machineTime'] ? Number(scope.row['machineTime']).toFixed(2) : scope.row['machineTime']}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('报工时间')" align="center" prop="feedbackTime"></el-table-column>
      </el-table>
    </div>
    
    <ItemSelect ref="ItemSelectRef" @onSelected="onItemSelect"/>
  </div>
</template>

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

import { getList, getFeedbackList, getProcessList } from "@/api/mes/proTable/productProcess";
import ItemSelect from "@/components/itemSelect/single.vue";

export default {
  name: "ScheduleSetupRule",
  components: {ItemSelect},
  dicts: [
  "mes_workorder_type",
  "mes_workorder_status"
],
  data() {
    return {
      loadingLeft: true,
      loadingRight: true,
      isShowSecond: false,
      highlightRow: null, // 当前高亮的行
      highlightRow1: null, // 当前高亮的行
      tbodysLeft:[],
      tbodysRight:[],
      tableHeightSecond: 0,
      tableHeight: 0,
      // 遮罩层
      loading: true,
      selectedRows: [],
      tabIndex: 0,
      // 选中数组
      ids: [],
      //dta列表
      dtaOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排产换型对照信息表格数据
      tbodys: [],
      theaders: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      daterangePurchaseDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        lineName: null,
        orderSerial: null,
        taskBatch: null,
        scheduleDate: null,
        pageSize: 10,
        defectStatus: true,
        workOrderStatus: [],
        lineName: null,
        "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._resizeHandler = this.calcTableHeight
    this.$nextTick(() => this.calcTableHeight())
    window.addEventListener('resize', this._resizeHandler)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this._resizeHandler)
  },
  watch: {
    isShowSecond() {
      this.$nextTick(() => this.calcTableHeight())
    },
    showSearch() {
      this.$nextTick(() => this.calcTableHeight())
    },
    total() {
      this.$nextTick(() => this.calcTableHeight())
    }
  },
  methods: {
    calcTableHeight() {
      const appMain = document.querySelector('.app-main')
      const viewportH = appMain ? appMain.clientHeight : window.innerHeight
      let used = 40
      const formEl = this.$refs.queryForm && this.$refs.queryForm.$el
      if (formEl && this.showSearch) {
        used += formEl.offsetHeight
      }
      const toolbarEl = this.$refs.toolbarRow && this.$refs.toolbarRow.$el
      if (toolbarEl) {
        used += toolbarEl.offsetHeight + 10
      }
      const paginationEl = this.$el.querySelector('.pagination-container')
      if (paginationEl && this.total > 0) {
        used += paginationEl.offsetHeight
      }
      const available = viewportH - used
      if (this.isShowSecond) {
        const mainH = Math.floor(available * 0.42)
        const secondH = Math.floor(available * 0.52)
        this.tableHeight = Math.max(200, mainH)
        this.tableHeightSecond = Math.max(150, secondH)
      } else {
        this.tableHeight = Math.max(200, available)
        this.tableHeightSecond = 0
      }
    },
    mainTableClick(row){
      this.loadingLeft = true;
      this.highlightRow = row;
      getProcessList({workorderCode: row.workorderCode, taskWorkunitId: row.taskWorkunitId}).then(response => {
        response.rows.forEach(element => {
          element['workorderCode'] = row.workorderCode
        });
        this.tbodysLeft = response.rows
        this.loadingLeft = false;
        this.isShowSecond = true
        this.$nextTick(() => this.calcTableHeight())
      });
      this.secondTableClick(row)
    },
    secondTableClick(row) {
      this.loadingRight = true;
      this.highlightRow1 = row;
      getFeedbackList({workorderCode: row.workorderCode, taskId: row.taskId, taskWorkunitId: row.taskWorkunitId}).then(response => {
        this.tbodysRight = response.rows;
        this.loadingRight = false;
      });
    },
    onItemSelect(row) {
      if (row != undefined) {
        this.queryParams.productName = row.itemName;
      }
    },
    tableRowClassName({ row, rowIndex }) {
      if(!row.workorderId || !this.highlightRow) return ''
      // 如果当前行是高亮行，则添加特定的类名
      if (row.workorderId === this.highlightRow.workorderId) {
        return 'highlight-row';
      }
      return '';
    },
    tableRowClassName1({ row, rowIndex }) {
      // 如果当前行是高亮行，则添加特定的类名
      if (row === this.highlightRow1) {
        return 'highlight-row';
      } if (row.status === '已完工') {
        return 'green';
      } if (row.status === '故障停工' || row.status === '暂停') {
        return 'red';
      }  if (row.status === '加工中') {
        return 'blue';
      }
      return '';
    },
    buildQueryParams() {
      const params = { ...this.queryParams, defectStatus: true }
      if (this.daterangePurchaseDate && this.daterangePurchaseDate.length > 0) {
        params.startDate = this.daterangePurchaseDate[0]
        params.endDate = this.daterangePurchaseDate[1]
      }
      if (params.scheduleDate && params.scheduleDate.length > 0) {
        params.scheduleDateFrom = params.scheduleDate[0]
        params.scheduleDateTo = params.scheduleDate[1]
      } else {
        params.scheduleDateFrom = null
        params.scheduleDateTo = null
      }
      delete params.scheduleDate
      return params
    },
    /** 查询排产换型对照信息列表 */
    getList() {
      this.loading = true;
      getList(this.buildQueryParams()).then(response => {
        this.tbodys = response.rows;
        this.total = response.total;
        this.loading = false;
        this.$nextTick(() => this.calcTableHeight())
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      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(){
      this.download(
        'report/pro/workOrderProgress/getList/export',
        this.buildQueryParams(),
        `productProcess_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
<style lang="scss" scoped>
.second-box{
  display: flex;
  margin-top: 10px;
}
.mys-container {
  .pagination-container {
    padding: 0px 20px !important;
  }
  ::v-deep .highlight-row {
    background-color: #e5eeff !important; 
    td {
      background-color: #e5eeff !important; 
    }
  }
  ::v-deep .green {
    background-color: #aaf8aa !important; 
    td {
      background-color: #aaf8aa !important; 
    }
  }
  ::v-deep .blue {
    background-color: #82ccf4 !important; 
    td {
      background-color: #82ccf4 !important; 
    }
  }
  ::v-deep .red {
    background-color: #f48d82 !important; 
    td {
      background-color: #f48d82 !important; 
    }
  }
}

</style>
