<!--
 * @Author: zhp
 * @Date: 2024-04-15 10:49:13
 * @LastEditTime: 2024-07-02 16:35:01
 * @LastEditors: DY
 * @Description:
-->
<template>
  <div style="display: flex; flex-direction: column; min-height: calc(100vh - 96px - 32px)">
    <ButtonNav v-show="false" :menus="['碲化镉工厂', '铜铟镓硒工厂']" :button-mode="true" @change="changeFactory" style="margin-top: -10px">
    </ButtonNav>
    <div class="app-container" style="height: auto; flex-grow: 1;">
      <el-form :model="listQuery" :inline="true" ref="dataForm" class="blueTip">
        <el-form-item v-if="facType === 0" label="工厂名称" prop="factorys">
          <el-select size="small" v-model="listQuery.factorys" placeholder="请选择工厂名称" multiple clearable>
            <el-option v-for="item in dhgfactoryList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-else label="工厂名称" prop="factorys">
          <el-select size="small" v-model="listQuery.factorys" placeholder="请选择工厂名称" multiple clearable>
            <el-option v-for="item in tyjxfactoryList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间维度" prop="date">
          <el-select size="small" clearable v-model="listQuery.date" placeholder="请选择" @change="clearTime">
            <el-option v-for="item in timeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="listQuery.date === 1 || listQuery.date === ''" label="时间范围" prop="reportTime">
          <el-date-picker size="small" clearable v-model="listQuery.reportTime" type="daterange" range-separator="至"
            start-placeholder="开始日期" value-format="yyyyMMdd" @change="changeDayTime" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-show="listQuery.date === 2" label="时间范围" prop="reportTime">
          <el-date-picker size="small" clearable v-model="start" type="week" format="yyyy 第 WW 周" placeholder="选择周"
            style="width: 180px" @change="onValueChange">
          </el-date-picker>
          至
          <el-date-picker size="small" clearable v-model="end" type="week" format="yyyy 第 WW 周"  placeholder="选择周"
            style="width: 180px" @change="onValueChange">
          </el-date-picker>
          <!-- <span v-if="start && end" style="margin-left: 10px">
            {{ date1 }} 至 {{ date2 }},共 {{ weekNum }} 周
          </span> -->
        </el-form-item>
        <el-form-item v-show="listQuery.date === 3" label="时间值" prop="reportTime">
          <el-date-picker size="small" v-model="listQuery.reportTime" type="monthrange" value-format="yyyyMM" range-separator="至" start-placeholder="开始月份"
            end-placeholder="结束月份" @change="changeTime">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-show="listQuery.date === 4" label="时间值" prop="reportTime">
          <el-date-picker size="small" clearable v-model="start" value-format="yyyy" type="year"
            placeholder="开始时间">
          </el-date-picker>
          ~
          <el-date-picker size="small" clearable v-model="end" value-format="yyyy" type="year" placeholder="结束时间"
            @change="getYear">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="玻璃类型" prop="type">
          <el-select v-model="listQuery.type" placeholder="请选择玻璃类型">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="玻璃类型" prop="type">
          <el-select v-model="listQuery.type" placeholder="请选择玻璃类型">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" size="small" @click="getDataList">查询</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="primary" size="small" plain @click="handleImport">导入</el-button>
          <el-button type="primary" size="small" plain @click="handleExport">导出</el-button>
          <el-button type="success" size="small" plain @click="addFactory">新增</el-button>
        </el-form-item>
      </el-form>
      <!-- <search-bar :formConfigs="formConfig" ref="searchBarForm" @headBtnClick="buttonClick" /> -->
      <base-table :table-props="tableProps" :page="listQuery.current" :limit="listQuery.size"
        :table-data="tableData">
        <method-btn v-if="tableBtn.length" slot="handleBtn" label="操作" :width="120" fixed="right"
          :method-list="tableBtn" @clickBtn="handleClick" />
      </base-table>
      <pagination
        :limit.sync="listQuery.size"
        :page.sync="listQuery.current"
        :total="listQuery.total"
        @pagination="getDataList"
      />
      <detail-or-update v-if="detailOrUpdateVisible" ref="detailOrUpdate" :ftype="facType" @destroy="detailOrUpdateVisible = false" />
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" :ftype="facType" @refreshDataList="getDataList" @destroy="addOrUpdateVisible = false" />

    </div>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :file-list="fileList"
        :disabled="upload.isUploading"
        :on-success="handleFileSuccess"
        :on-progress="handleFileUploadProgress"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <!-- <el-upload
        ref="upload"
        class="upload-demo"
        action="#"
        :limit="1"
        :file-list="fileList"
        :auto-upload="false"
        :http-request="handleFileSuccess"> -->
        <!-- <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传.xlsx, .xls文件,且不超过500kb</div>
      </el-upload> -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- <inputTable :date="date" :data="tableData" :time="[startTimeStamp, endTimeStamp]" :sum="all"
      :type="listQuery.reportType" @refreshDataList="getDataList" /> -->
    <!-- <pagination
			:limit.sync="listQuery.pageSize"
			:page.sync="listQuery.pageNo"
			:total="listQuery.total"
			@pagination="getDataList" /> -->
  </div>
</template>

<script>
import { parseTime } from '@/utils/ruoyi';
import { prodTargetDiPage, prodTargetToPage, exportDiTargetExcel, exportToTargetExcel, delTarget, importToTarget, importDiTarget } from '@/api/produceData';
// import inputTable from './inputTable.vue';
import moment from 'moment'
import ButtonNav from '@/components/ButtonNav'
import basicPage from '@/mixins/basic-page'
import detailOrUpdate from './detail-or-updata';
import addOrUpdate from './add-or-updata';
import { factoryList, dhgfactoryList, tyjxfactoryList } from "@/utils/constants";
import {getBaseHeader} from "@/utils/request";


// import FileSaver from 'file-saver'
// import * as XLSX from 'xlsx'
export default {
  components: { ButtonNav, detailOrUpdate, addOrUpdate },
  mixins: [basicPage],
	data() {
    return {
      factoryList,
      dhgfactoryList,
      tyjxfactoryList,
      currentMenu: '碲化镉工厂',
      fileList: [],
      start: undefined,
      end: undefined,
      listQuery: {
        size: 10,
        current: 1,
        factorys: null,
        total: 0,
        date: 3,
        beginTime: undefined,
        endTime: undefined,
        reportTime: []
      },
      detailOrUpdateVisible: false,
      addOrUpdateVisible:false,
      date1: undefined,
      date2: undefined,
      // 用户导入参数
      upload: {
        // 是否显示弹出层(用户导入)
        open: false,
        // 弹出层标题(用户导入)
        title: "导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // updateSupport: 0,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/admin-api/ip/prod-target/di-target-import-excel'
      },
      tableBtn: [
        {
            type: 'detail',
            btnName: '详情',
        },
        {
          type: 'edit',
          btnName: '修改',
        },
        {
          type: 'delete',
          btnName: '删除',
        }
      ].filter((v) => v),
      typeList: [
        {
          name: '芯片',
          id: 0,
        },
        {
          name: '标准组件',
          id: 1,
        },
        {
          name: 'BIPV产品',
          id: 2,
        },
      ],
			urlOptions: {
				// getDataListURL: getGlassPage,
				// exportURL: exportGlasscExcel
      },
      mainFormConfig: [
      	{
          type: 'select',
          label: '工单',
          placeholder: '请选择工单',
          param: 'workOrderId',
          selectOptions: [],
        },
        // {
        // 	type: 'select',
        // 	label: '产线',
        // 	placeholder: '请选择产线',
        // 	param: 'lineId',
        // 	selectOptions: [],
        // },
        // 选项切换
        // {
        // 	type: 'select',
        // 	label: '时间类型',
        // 	param: 'dateFilterType',
        // 	defaultSelect: 0,
        // 	selectOptions: [
        // 		{ id: 0, name: '按时间段' },
        // 		{ id: 1, name: '按日期' },
        // 	],
        // 	index: 2,
        // 	extraOptions: [
        {
          // parent: 'dateFilterType',
          // 时间段选择
          type: 'datePicker',
          label: '时间段',
          // dateType: 'datetimerange',
          dateType: 'datetimerange',
          format: 'yyyy-MM-dd HH:mm:ss',
          valueFormat: 'yyyy-MM-ddTHH:mm:ss',
          rangeSeparator: '-',
          rangeSeparator: '-',
          startPlaceholder: '开始时间',
          endPlaceholder: '结束时间',
          param: 'recordTime',
        },
        // 		{
        // 			parent: 'dateFilterType',
        // 			// 日期选择
        // 			type: 'datePicker',
        // 			// label: '日期',
        // 			dateType: 'date',
        // 			placeholder: '选择日期',
        // 			format: 'yyyy-MM-dd',
        // 			valueFormat: 'yyyy-MM-dd',
        // 			param: 'timeday',
        // 		},
        // 	],
        // },
        {
          type:'button',
          btnName: '查询',
          name: 'search',
          color: 'primary',
        },
         {
          type:'separate'
        },
        // {
        //   type: this.$auth.hasPermi(
        //     'analysis:equipment:export'
        //   )
        //     ? 'separate'
        //     : '',
        // },
        {
          type:'button',
          btnName: '导出',
          name: 'export',
          color: 'warning',
        },
      ],
      formConfig: [
        {
          type: 'title',
          label: '成本管理',
        },
      ],
      timeList: [
        {
          value: 1,
          label: '日'
        },
        {
          value: 2,
          label: '周'
        },
        {
          value: 3,
          label: '月'
        },
        {
          value: 4,
          label: '年'
        }
      ],
      tableProps: [
        {
          prop: 'factory',
          label: '工厂名称',
          filter: (val) => factoryList[val],
          minWidth: 200,
          showOverflowtooltip: true
        },
        {
          prop: 'targetTime',
          label: '目标时间',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'updateTime',
          label: '提交时间',
          filter: parseTime,
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'ftoInput',
          label: 'FTO投入量(片)',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'chipYield',
          label: '芯片产量(片)',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'chipAveragePower',
          label: '芯片平均功率(W)',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'chipYieldRate',
          label: '芯片良率(%)',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'chipTotalPower',
          label: '芯片总功率(KW)',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'chipCssMarriageRate',
          label: 'CSS稼动率(%)',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'chipOee',
          label: '芯片段OEE(%)',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'chipCapacityUtilizationRate',
          label: '芯片产能利用率(%)',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'chipAnnualAverageProduction',
          label: '芯片人均产量(片/人)',
          minWidth: 180,
          showOverflowtooltip: true
        },
        {
          prop: 'chipBom',
          label: '芯片BOM',
          minWidth: 150,
          showOverflowtooltip: true
        },
      ],
      // timeSelect:'month',
      // startTimeStamp:null, //开始时间
      // endTimeStamp:null, //结束时间
      // date:'凯盛玻璃控股成员企业2024生产数据',
			// reportTime: '',
			// startTimeStamp: '',
			// endTimeStamp: '',
      tableData: [],
      facType: 0
			// proLineList: [],
			// all: {}
		};
  },
  computed: {
    weekNum() {
      return Math.round((this.end - this.start) / (24 * 60 * 60 * 1000 * 7)) + 1
    },
  },
  watch: {
    facType(value) {
      if (value === 0) {
        this.$set(this.tableProps, 3, {
          prop: 'ftoInput',
          label: 'FTO投入量(片)',
          minWidth: 150,
          showOverflowtooltip: true
        })
        this.upload.url = process.env.VUE_APP_BASE_API + '/admin-api/ip/prod-target/di-target-import-excel'
      } else {
        this.$set(this.tableProps, 3, {
          prop: 'molybdenumElectrodeInput',
          label: '钼电极投入量(片)',
          minWidth: 150,
          showOverflowtooltip: true
        })
        this.upload.url = process.env.VUE_APP_BASE_API + '/admin-api/ip/prod-target/to-target-import-excel'
      }
    }
  },
	created() {
    const currentMonth = new Date()
    this.listQuery.reportTime = [moment(currentMonth).format('yyyyMM'), moment(currentMonth).format('yyyyMM')]
    this.changeTime()
	},
  methods: {
    clearTime() {
      this.listQuery.beginTime = undefined
      this.listQuery.endTime = undefined
      this.listQuery.reportTime = []
      this.start = undefined
      this.end = undefined
    },
    handleImport() {
      this.upload.title = "生产目标导入";
      this.upload.open = true;
      this.fileList = []
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
        // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 0) {
        this.$modal.msgError(response.msg)
        return;
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$message.success('导入成功!')
      this.getDataList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    addFactory() {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init();
      });
    },
    changeFactory($event) {
      this.currentMenu = $event
      this.facType = this.currentMenu === '碲化镉工厂' ? 0 : 1
      this.getDataList()
    },
    handleClick(val) {
      if (val.type === "edit") {
        this.addOrUpdateVisible = true;
        // this.addOrEditTitle = "编辑";
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(val.data.id);
        });
      } else if (val.type === "delete") {
        this.deleteHandle(val.data.id, val.data.factory, val.data._pageIndex)
      } else {
        this.otherMethods(val)
      }
    },
    // 删除
    deleteHandle(id, name, index) {
      this.$confirm('是否确认删除工厂名称为' + factoryList[name] + '的数据项?', "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delTarget(id).then(({ data }) => {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              },
            });
          });
        })
        .catch(() => { });
    },
    otherMethods(val) {
      this.detailOrUpdateVisible = true;
      this.addOrEditTitle = "详情";
      this.$nextTick(() => {
        this.$refs.detailOrUpdate.init(val.data.id);
      });
    },
    getYear(e) {
      if (this.end && Number(this.end) - Number(this.start) > 10) {
        this.$message({
          message: '年份起止时间不能超过十年',
          type: 'warning'
        });
        this.start = undefined
        this.end = undefined
        // console.log();
      } else {
        if (Number(this.end) < Number(this.start)) {
          this.$message({
            message: '结束年份不能小于开始年份',
            type: 'warning'
          });
          this.start = undefined
          this.end = undefined
        } else {
          this.listQuery.beginTime = Number(this.start)
          this.listQuery.endTime = Number(this.end)
        }
      }
      if (!this.start && !this.end) {
        this.listQuery.beginTime = undefined
        this.listQuery.endTime = undefined
      }
      // console.log(e);
    },
    changeTime() {
      if (this.listQuery.reportTime) {
        const years = Number(this.listQuery.reportTime[1].slice(0, 4)) - Number(this.listQuery.reportTime[0].slice(0, 4))
        const months = Number(this.listQuery.reportTime[1].slice(4)) - Number(this.listQuery.reportTime[0].slice(4))
        if (years * 12 + months > 24) {
          this.$message({
            message: '时间范围不能超过24个月',
            type: 'warning'
          });
          this.listQuery.reportTime = [];
        } else {
          this.listQuery.beginTime = Number(this.listQuery.reportTime[0])
          this.listQuery.endTime = Number(this.listQuery.reportTime[1])
        }
      } else {
        this.listQuery.beginTime = undefined
        this.listQuery.endTime = undefined
      }
    },
    onValueChange(picker, k) { // 选中近k周后触发的操作
      if (this.start && this.end) {
        this.date1 = moment(this.start.getTime() - 24 * 60 * 60 * 1000).format('YYYY-MM-DD HH:mm:ss')
        this.date2 = moment(this.end.getTime() + 5 * 24 * 60 * 60 * 1000).format('YYYY-MM-DD HH:mm:ss')
        const numDays = (new Date(this.date2).getTime() - new Date(this.date1).getTime()) / (24 * 3600 * 1000);
        if (numDays > 168) {
          console.log(numDays)
          this.$message({
            message: '周范围不能超过24周',
            type: 'warning'
          });
        } else {
          this.listQuery.beginTime = Number(moment(this.start.getTime()).format('YYYYWW'))
          this.listQuery.endTime = Number(moment(this.end.getTime()).format('YYYYWW'))
        }
      }
      if (!this.start && !this.end) {
        this.listQuery.beginTime = undefined
        this.listQuery.endTime = undefined
      }
    },
    changeDayTime() {
      if (this.listQuery.reportTime) {
        const numDays = Number(this.listQuery.reportTime[1]) - Number(this.listQuery.reportTime[0])
        if (numDays > 30) {
          this.$message({
            message: '时间范围不能超过30天',
            type: 'warning'
          });
          this.listQuery.reportTime = [];
        } else {
          this.listQuery.beginTime = Number(this.listQuery.reportTime[0])
          this.listQuery.endTime = Number(this.listQuery.reportTime[1])
        }
      } else {
        this.listQuery.beginTime = undefined
        this.listQuery.endTime = undefined
      }
    },
    async getDataList() {
      if (this.currentMenu === '碲化镉工厂') {
        await prodTargetDiPage(this.listQuery).then(res => {
          if (res.code === 0) {
            this.tableData = res.data.records
            this.listQuery.total = res.data.total
          }
        })
      } else {
        await prodTargetToPage(this.listQuery).then(res => {
          if (res.code === 0) {
            this.tableData = res.data.records
            this.tableData.forEach(item => {
              const year = item.targetYear ? item.targetYear + '年' : ''
              const month = item.targetMonth ? item.targetMonth + '月' : ''
              item.tagertTime = year + month
            })
            this.listQuery.total = res.data.total
          }
        })
      }
    },
		buttonClick(val) {
			this.listQuery.reportTime = val.reportTime ? val.reportTime : undefined;
			switch (val.btnName) {
				case 'search':
					this.listQuery.current = 1;
					this.listQuery.size = 10;
					this.getDataList();
					break;
				case 'export':
					this.handleExport();
					break;
				default:
					console.log(val);
			}
		},
		/** 导出按钮操作 */
    handleExport() {
      const queryParams = this.listQuery;
      queryParams.current = 1
      queryParams.size = 999
      if (this.facType === 0) {
        this.$modal.confirm('是否确认导出所有数据项?').then(() => {
          this.exportLoading = true;
          return exportDiTargetExcel(queryParams);
        }).then(response => {
          this.$download.excel(response, '碲化镉工厂生产目标数据.xls');
          this.exportLoading = false;
        }).catch(() => {});
      } else {
        this.$modal.confirm('是否确认导出所有数据项?').then(() => {
          this.exportLoading = true;
          return exportToTargetExcel(queryParams);
        }).then(response => {
          this.$download.excel(response, '铜铟镓硒工厂生产目标数据.xls');
          this.exportLoading = false;
        }).catch(() => {});
      }
    }
	},
};
</script>

<style>
/* .blueTip { */
	/* padding-bottom: 10px; */
/* } */
.blueTip .el-date-editor .el-range__icon {
  font-size: 16px;
  color: #0b58ff;
}
.blueTip .el-input__prefix .el-icon-date {
  font-size: 16px;
  color: #0b58ff;
}
.blueTip .el-input__prefix .el-icon-time {
  font-size: 16px;
  color: #0b58ff;
}
.blueTip::before{
  display: inline-block;
  content: '';
  width: 4px;
  height: 18px;
  background: #0B58FF;
  border-radius: 1px;
  margin-right: 8PX;
  margin-top: 8px;
}
.app-container {
  margin: 0;
  background-color: #fff;
  border-radius: 4px;
  padding: 16px 16px 0;
  height: calc(100vh - 134px);
  overflow: auto;
}
</style>