<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="location">
        <el-input v-model="queryParams.location" placeholder="请输入存储位置" />
      </el-form-item>
      <el-form-item label="物料名称" prop="itemName">
        <el-input v-model="queryParams.itemName" placeholder="请输入物料名称" />
      </el-form-item>
      <el-form-item label="物料编码" prop="sapItemCode">
        <el-input v-model="queryParams.sapItemCode" placeholder="请输入物料编码" />
      </el-form-item>
      <el-form-item label="刀模SN" prop="toolCode">
        <el-input v-model="queryParams.toolCode" placeholder="请输入刀模SN" />
      </el-form-item>
      <el-form-item :label="'履历状态'" prop="operationType">
        <el-select v-model="queryParams.operationType" clearable :placeholder="'请选择状态'">
          <el-option v-for="dict in operationTypeList" :key="dict.value" :label="dict.label" :value="dict.value">
          </el-option>
        </el-select>
      </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">
              <span v-if="item.value == 'operationType'">{{ operationTypeData[scope.row[item.value]] }}</span>
              <span v-else>{{ scope.row[item.value] }}</span>
            </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="4">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ '查询' }}</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">
          <el-table-column :label="item.label" align="center" :prop="item.value" :width="item.width" v-for="(item, index) in theaders1"
            :key="index">
            <template slot-scope="scope">
              <span v-if="item.value == 'warning10' || item.value == 'warning30'">{{ scope.row[item.value] ? '是' : '否'
                }}</span>
              <span v-else-if="item.value == 'warning30Proportion'">{{ scope.row['warning30Sum'] /
                scope.row['sum'] }}%</span>
              <span v-else-if="item.value == 'warning10Proportion'">{{ scope.row['warning10Sum'] /
                scope.row['sum'] }}%</span>
              <span v-else-if="item.value == 'warningNegativeProportion'">{{ scope.row['warningNegativeSum'] /
                scope.row['sum'] }}%</span>
              <span v-else>{{ scope.row[item.value] }}</span>
            </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>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { getResumeStatusApi, getListApi, getSnMaintenanceListApi, getMaterialMaintenanceListApi, getSnLifecycleListApi } from "@/api/mes/proTable/knifeMoldUsage";

export default {
  name: "KnifeMoldUsage",
  data() {
    return {
      // 遮罩层
      loading: true,
      selectedRows: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排产换型对照信息表格数据
      tbodys: [],
      theaders: [],
      tbodys1: [],
      theaders1: [],
      tabIndex: 0,
      statisisType: '物料维保预警统计',
      statisisList: ['物料维保预警统计', 'SN维保预警清单30%', 'SN维保预警清单10%', 'SN生命周期统计'],
      operationTypeData: [],
      operationTypeList: [],
      tableHeight: 0,
      daterangePurchaseDate: [dayjs().startOf('month').format('YYYY-MM-DD'), dayjs().endOf('month').format('YYYY-MM-DD')],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        location: null,
        itemName: null,
        sapItemCode: null,
        location: null,
        operationType: 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.getResumeStatus();
    this.getList();
  },
  methods: {
    onWorkunitSelect(row) {
      if (row != undefined) {
        this.queryParams.workunitName = row.workunitName;
      }
    },
    tabClick(val) {
      console.log('this.tabIndex', this.tabIndex, val)
      this.tabIndex = val.index
      this.resetForm("queryForm")
      this.getList()
      this.$nextTick(() => {
        this._resizeHandler()
      })
    },
    getResumeStatus() {
      getResumeStatusApi().then((response) => {
        this.operationTypeData = response.data;
        this.operationTypeList = Object.keys(response.data).map((item) => {
          return {
            label: response.data[item],
            value: item
          }
        })
      })
    },
    /** 查询排产换型对照信息列表 */
    getList() {
      this.loading = 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 = getListApi
      if (Number(this.tabIndex) === 0) {
        this.theaders = [
          { label: '物料编码', value: 'sapItemCode', width: '200px' },
          { label: '刀模SN', value: 'toolCode', width: '150px' },
          { label: '履历状态', value: 'operationType', width: '120px' },
          { label: '关联单据类型', value: 'orderType', width: '120px' },
          { label: '增减寿命值（次）', value: 'quantityDifference', width: '140px' },
          { label: '剩余次数', value: 'lifeTime', width: '80px' },
          { label: '所在位置', value: 'location', width: '100px' },
          { label: '操作人', value: 'createBy', width: '120px' },
          { label: '操作时间', value: 'createTime', width: '160px' },
        ]
      }
      if (Number(this.tabIndex) === 1) {
        if (this.statisisType === '物料维保预警统计') {
          api = getMaterialMaintenanceListApi
          this.theaders1 = [
            { label: '物料编码', value: 'sapItemCode', width: '200px' },
            { label: '物料名称', value: 'itemName', width: '200px' },
            { label: 'SN数量', value: 'sum', width: '100px' },
            { label: '寿命低于30%数量', value: 'warning30Sum', width: '140px' },
            { label: '寿命低于30%占比', value: 'warning30Proportion', width: '140px' },
            { label: '寿命低于10%数量', value: 'warning10Sum', width: '140px' },
            { label: '寿命低于10%占比', value: 'warning10Proportion', width: '140px' },
            { label: '寿命负值数量', value: 'warningNegativeSum', width: '100px' },
            { label: '寿命负值占比', value: 'warningNegativeProportion', width: '100px' },
          ]
        } else if (this.statisisType === 'SN维保预警清单30%') {
          this.theaders1 = [
            { label: '刀模SN', value: 'toolCode' },
            { label: '初始寿命', value: 'initialLifeTime', width: '100px' },
            { label: '剩余寿命', value: 'lifeTime', width: '100px' },
            { label: '所在位置', value: 'location' },
            { label: '是否寿命低于30%', value: 'warning30', width: '140px' },
          ]
          api = getSnMaintenanceListApi
        } else if (this.statisisType === 'SN维保预警清单10%') {
          this.theaders1 = [
            { label: '刀模SN', value: 'toolCode' },
            { label: '初始寿命', value: 'initialLifeTime', width: '200px' },
            { label: '剩余寿命', value: 'lifeTime', width: '200px' },
            { label: '所在位置', value: 'location' },
            { label: '是否寿命低于10%', value: 'warning10', width: '140px' },
          ]
          api = getSnMaintenanceListApi
        } else if (this.statisisType === 'SN生命周期统计') {
          this.theaders1 = [
            { label: '刀模SN', value: 'toolCode', width: '150px' },
            { label: '创建时间', value: 'createTime', width: '140px' },
            { label: '初始寿命', value: 'initialLifeTime', width: '120px' },
            { label: '累计使用次数', value: 'countSum', width: '140px' },
            { label: '累计使用寿命', value: 'lifeTimeSum', width: '140px' },
            { label: '累计维保次数', value: 'statisticsCountSum', width: '140px' },
            { label: '累计维保增减寿命', value: 'statisticsLifeTimeSum', width: '140px' },
            { label: '报废时间', value: 'scrapTime', width: '140px' },
            { label: '报废人', value: 'scrapBy', width: '100px' },
          ]
          api = getSnLifecycleListApi
        }
      }
      api(this.queryParams).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.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/getListByWorkshop/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/getListByUser/export'
      } else if (this.statisisType === '工单') {
        apiName = 'report/pro/feedback/getListByWorkOrder/export'
      }
      this.download(
        apiName,
        {
          ...this.queryParams,
        },
        `statistAnaly_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
