<template>
  <div class="app-container">
    <!--查询表单-->
    <el-card class="operate-container" shadow="never">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="所属产线">
          <el-select
            v-model="zoneId"
            clearable
            placeholder="请选择"
            style="width: 100%"
            @change="getResourceList()"
          >
            <el-option
              v-for="(item, index) in zoneList"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务类型">
          <el-select
            v-model="taskType"
            clearable
            placeholder="请选择"
            style="width: 100%"
            @change="getResourceList()"
          >
            <el-option
              v-for="(item, index) in taskTypeList"
              :key="index"
              :label="item.name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择设备">
          <el-select
            v-model="searchObj.resourceId"
            clearable
            placeholder="请选择"
            style="width: 100%"            
          >
            <el-option
              v-for="(item, index) in resourceIds"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产时间">
          <el-date-picker
            v-model="searchObj.startDate"
            placeholder="开始时间"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="-">
          <el-date-picker
            v-model="searchObj.endDate"
            placeholder="结束时间"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="生产月份">
          <el-date-picker
            v-model="searchObj.month"
            type="month"
            placeholder="选择月"
            value-format="yyyy-MM"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="生产年份">
          <el-date-picker
            v-model="searchObj.years"
            type="year"
            placeholder="选择年"
            value-format="yyyy"
          >
          </el-date-picker>
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fetch()"
          >查询</el-button
        >
        <el-button type="default" @click="resetData()">清空</el-button>

        <el-button type="primary" icon="el-icon-download" @click="exportData()" v-show="false" >导出</el-button>
      </el-form>
    </el-card>
    <!-- 列表数据 -->
    <el-table
      :key="tableKey"
      ref="table"
      :data="tableData"
      border
      fit
      style="width: 100%"
      @selection-change="onSelectChange"      
    >
      <el-table-column
        :label="$t('common.serialNo')"
        width="55px"
        align="center"
      >
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="设备资源生产表" :resizable="false" align="center">
        <!--产线-->
        <el-table-column
          prop="zoneName"
          :label="$t('statisticalAnalysis.table.deviceResource.zoneName')"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <!--分配设备-->
        <el-table-column
          prop="resourceName"
          :label="$t('statisticalAnalysis.table.deviceResource.resourceName')"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <!--总数量-->
        <el-table-column
          prop="totalNum"
          :label="$t('statisticalAnalysis.table.deviceResource.totalNum')"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <!--日期-->
        <el-table-column
          prop="time"
          :label="$t('statisticalAnalysis.table.deviceResource.time')"
          :show-overflow-tooltip="true"
        >
        </el-table-column>

        <!--理论加工周期-->
        <el-table-column
          prop="totalExpectTime"
          :label="$t('statisticalAnalysis.table.deviceResource.totalExpectTime')"
          :show-overflow-tooltip="true"
        >
        </el-table-column>

        <!--实际加工周期-->
        <el-table-column
          prop="totalRealTime"          
          :label="$t('statisticalAnalysis.table.deviceResource.totalRealTime')"
          :show-overflow-tooltip="true"
        >
        </el-table-column>

        <!--平均理论加工周期-->
        <el-table-column
          prop="avgExpectTime"
          width="150px"          
          :label="$t('statisticalAnalysis.table.deviceResource.avgExpectTime')"
          :show-overflow-tooltip="true"
        >
        </el-table-column>

        <!--平均实际加工周期-->
        <el-table-column
          prop="avgRealTime"
          width="150px"
          :label="$t('statisticalAnalysis.table.deviceResource.avgRealTime')"
          :show-overflow-tooltip="true"
        >
        </el-table-column>

        <!--操作-->
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="fetchDataById(scope.row)"
              >查看详情</el-button
            >
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <p style="color: #E96767;size: 10px;float: right">生产总数：{{totalNum}}</p>
    <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      style="padding: 30px 0; text-align: center"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="changePageSize"
      @current-change="changeCurrentPage"
    />



    <el-dialog title="产品加工详情" :close-on-click-modal="false" :visible.sync="dialogVisible"  style="width: 110%; margin-top: 20px">
      <el-table
        :key="tableKey"
        ref="table"
        :data="formData"
        border
        fit
        style="width: 100%"
      >
        <!--订单号-->
        <el-table-column
          prop="orderNo"
          :label="$t('statisticalAnalysis.table.deviceResourceDetail.orderNo')"
          :show-overflow-tooltip="true"
          width="140"
        >
        </el-table-column>
        <!--产线名称-->
        <el-table-column
          prop="zoneName"
          :label="$t('statisticalAnalysis.table.deviceResourceDetail.zoneName')"
          :show-overflow-tooltip="true"
          width="145"
        >
        </el-table-column>
        <!--分配设备名称-->
        <el-table-column
          prop="resourceName"
          :label="$t('statisticalAnalysis.table.deviceResourceDetail.resourceName')"
          :show-overflow-tooltip="true"
          width="160"
        >
        </el-table-column>
        <!--产品名称-->
        <el-table-column
          prop="bomName"
          :label="$t('statisticalAnalysis.table.deviceResourceDetail.bomName')"
          :show-overflow-tooltip="true"
          width="130"
        >
        </el-table-column>
        <!--工序-->
        <el-table-column
          prop="procedureNo"
          :label="$t('statisticalAnalysis.table.deviceResourceDetail.procedureNo')"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <!--开始时间-->
        <el-table-column
          prop="startTime"
          :label="$t('statisticalAnalysis.table.deviceResourceDetail.startTime')"
          :show-overflow-tooltip="true"
          width="160"
        >
        </el-table-column>
        <!--结束时间-->
        <el-table-column
          prop="endTime"
          :label="$t('statisticalAnalysis.table.deviceResourceDetail.endTime')"
          :show-overflow-tooltip="true"
          width="160"
        >
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        :current-page="page2"
        :total="total2"
        :page-size="limit2"
        :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
        style="padding: 30px 0; text-align: center"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="changePageSize2"
        @current-change="changeCurrentPage2"
      />
    </el-dialog>
  </div>
</template>

<script>
// 【产品加工汇总】-API
import productlineAvailabilityApi from "@/api/statisticalAnalysis/productlineAvailability";
// 【弹出框】elementui组件
import elDragDialog from "@/directive/el-drag-dialog";
import Pagination from "@/components/Pagination";
import areaMgrApi from "@/api/resourceProductMgr/areaMgr";
export default {
  name: "productStatistics",
  directives: {
    elDragDialog,
  },
  components: {},
  data() {
    return {
      tableData: [], // 讲师列表
      formData: [],
      total: 0, // 总记录数
      page: 1, // 当前页码
      limit: 10, // 每页记录数
      page2: 1, // 当前页码
      limit2: 10, // 每页记录数
      total2: 0, // 总记录数
      searchObj: {}, // 查询条件
      dialogVisible: false, //是否弹框
      zoneList: [],
      row2: {},
      totalNum: 0
    };
  },
  computed: {},
  // 实例已经在内存中创建好，此时data和methods已将ok,如果要操作data中的数据或是调用methods中的方法，最早只能在created中操作
  created() {
    // 加载列表数据
    this.fetch();
    this.getZoneList();
  },
  watch: {
    loadingId: {
      handler(val, oldVal) {
        // 加载列表数据
        this.fetch();
      },
    },
    loadingDate: {
      handler(val, oldVal) {
        // 加载列表数据
        this.fetch();
      },
    },
  },
  mounted() {},
  methods: {
    view(row) {
      this.$refs.view.setOperatorDetailPerformance(row);
      this.operatorViewVisible = true;
    },
    fetch() {
      let index = 0;
      if(this.searchObj.startDate) index++;
      if(this.searchObj.month) index++;
      if(this.searchObj.years) index++;

      if(index>1) {
        this.$message({
          message: "时间，月份，年份只能选择一个",
          type: "warning"
        })
        return
      }
      this.tableKey = !this.tableKey;
      productlineAvailabilityApi
        .deviceResourceSum(this.page, this.limit, this.searchObj)
        .then((response) => {
          const res = response.data;
          this.tableData = (res.data || []).records;
          this.totalNum = 0
          if(this.tableData){
            this.tableData.forEach(item => {
              this.totalNum += Number(item.totalNum)
            })
          }
          this.total = (res.data || []).total;
        });
    },
    //根据id查询
    fetchDataById(row) {
      //弹出框
      this.row2 = row
      this.dialogVisible = true;
      const obj = {
        resourceId: row.resourceId,
        zoneId: row.zoneId,
        startDate: this.searchObj.startDate,
        endDate: this.searchObj.endDate,
        month: this.searchObj.month,
        years: this.searchObj.years
      }
      this.tableKey = !this.tableKey;
      productlineAvailabilityApi
        .deviceResourceDetail(this.page2,this.limit2,obj)
        .then((response) => {
          const res = response.data;
          this.formData = (res.data || []).records;
          this.total2 = (res.data || []).total;
        });
    },
    // 每页记录数改变，size：回调参数，表示当前选中的“每页条数”
    changePageSize(size) {
      this.limit = size;
      this.fetch();
    },
    // 改变页码，page：回调参数，表示当前选中的“页码”
    changeCurrentPage(page) {
      this.page = page;
      this.fetch();
    },
    changePageSize2(size) {
      this.limit2 = size;
      console.log("执行")
      this.fetchDataById(this.row2);
    },
    changeCurrentPage2(page) {
      this.page2 = page;
      console.log("执行")
      this.fetchDataById(this.row2);
    },
    //清空
    resetData() {
      this.searchObj = {};
      this.fetch();
    },
    cellClick(row, column) {
      if (column["columnKey"] === "operation") {
        return;
      }
      let flag = false;
      this.selection.forEach((item) => {
        if (item.id === row.id) {
          flag = true;
          this.$refs.table.toggleRowSelection(row);
        }
      });

      if (!flag) {
        this.$refs.table.toggleRowSelection(row, true);
      }
    },
    onSelectChange(selection) {
      this.selection = selection;
    },
    getZoneList() {
      areaMgrApi.getList({ status: 1 }).then((res) => {
        res = res.data;
        if (res.isSuccess) {
          if(res.data){
            this.zoneList = res.data.filter(item => item.name.indexOf('保障') ==-1)
          }
        }
      });
    },
    //导出
    exportData() {
      productlineAvailabilityApi.exportTaskResourceSum(this.searchObj).then((res) => {
        if (!res) return;
        const blob = new Blob([res.data], {
          type: "application/vnd.ms-excel;",
        });
        const a = document.createElement("a");
        // 生成文件路径
        let href = window.URL.createObjectURL(blob);
        a.href = href;
        // 文件名中有中文 则对文件名进行转码
        a.download = decodeURIComponent("任务资源汇总导出");
        // 利用a标签做下载
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(href);
        this.allloading = false;
      });
    },
    //
     objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
		  const _row = this.flitterData(this.formData).one[rowIndex];
		  const _col = _row > 0 ? 1 : 0;
		  return {
		    rowspan: _row,
		    colspan: _col,
		  };
		}
	},
	/**合并表格的第一列，处理表格数据 */
	flitterData(arr) {
	  let spanOneArr = [];
	  let concatOne = 0;
	  arr.forEach((item, index) => {
	    if (index === 0) {
	      spanOneArr.push(1);
	    } else {
	    //注意这里的quarterly是表格绑定的字段，根据自己的需求来改
	      if (item.quarterly === arr[index - 1].quarterly) {
	        //第一列需合并相同内容的判断条件
	        spanOneArr[concatOne] += 1;
	        spanOneArr.push(0);
	      } else {
	        spanOneArr.push(1);
	        concatOne = index;
	      }
	    }
	  });
	  return {
	    one: spanOneArr,
	  };

     }
  },
};
</script>

<style lang="scss" scoped>
.rowBtn {
  margin: 0 5px;
  color: #1890ff;
}

.rowBtn:hover {
  opacity: 0.7;
}
</style>
