<!--
 * @Author: zhp
 * @Date: 2024-04-15 10:49:13
 * @LastEditTime: 2024-07-26 14:28:19
 * @LastEditors: zhp
 * @Description:
-->
<template>
  <div style="display: flex; flex-direction: column; min-height: calc(100vh - 96px - 32px)">
    <div class="app-container" style="height: auto; flex-grow: 1;">
      <el-form :model="listQuery" :inline="true" ref="dataForm" class="blueTip">
        <el-form-item label="时间维度" prop="start">
          <el-cascader clearable :options="options" v-model="listQuery.start"
            :props="{ multiple: false, emitPath: false }" @change="handleChange" placeholder="选择开始年份和期数" />
        </el-form-item>
        <el-form-item label-width="0" prop="end">
          <el-cascader clearable :options="options" v-model="listQuery.end"
            :props="{ multiple: false, emitPath: false }" @change="handleChange" placeholder="选择结束年份和期数" />
        </el-form-item>
        <el-form-item label="成本中心名称" prop="center">
          <el-input v-model="listQuery.center" placeholder="请填写成本中心名称" clearable>
          </el-input>
        </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 :row-key="(record, index) => { return record.in }" border :table-props="tableProps"
        :page="listQuery.pageNo" :limit="listQuery.pageSize" :table-data="tableData" :max-height="tableH">
        <!-- <method-btn v-if="tableBtn.length" slot="handleBtn" label="操作" :width="120" fixed="right"
          :method-list="tableBtn" @clickBtn="handleClick" /> -->
      </base-table>
      <pagination :limit.sync="listQuery.pageSize" :page.sync="listQuery.pageNo" :total="listQuery.total"
        @pagination="getDataList" />
    </div>

    <!-- 用户导入对话框 -->

    <!-- <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 { getCostMainPage, exportExcel } from '@/api/cost';
// import inputTable from './inputTable.vue';
import moment from 'moment'

// 设置语言
// 引入组件
// Vue.component(DatePicker.months, DatePicker)
// Vue.component(Select.name, Select)
// 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 { factoryList } from "@/utils/constants";
// import tableHeightMixin from "@/mixins/tableHeightMixin";

// import FileSaver from 'file-saver'
// import * as XLSX from 'xlsx'
export default {
  // components: { ButtonNav, detailOrUpdate, addOrUpdate },
  mixins: [basicPage],
  data() {
    const currentYear = new Date().getFullYear();
    const startYear = currentYear - 10;
    const endYear = currentYear + 10;
    const options = [];
    for (let year = startYear; year <= endYear; year++) {
      const yearOptions = [];
      for (let period = 1; period <= 12; period++) {
        yearOptions.push({
          value: `${year}${('0' + period + '期').slice(-3)}`,
          label: `${year}${('0' + period + '期').slice(-3)}`
        });
      }
      options.push({
        value: year,
        label: year,
        children: yearOptions
      });
    }
    return {
      start: undefined,
      end: undefined,
      // selectedValues: [],
      options,
      tableH: this.tableHeight(300),
      listQuery: {
        pageSize: 20,
        pageNo: 1,
        total: 0,
        center: undefined,
        start: undefined,
        end: undefined,
        yearPhaseStart:undefined,
        yearPhaseEnd:undefined,
      },
      // 用户导入参数
      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: '成本管理',
        },
      ],
      mDTypeList: [
        {
          value: 0,
          label: '物料编码'
        },
        {
          value: 1,
          label: '物料名称'
        }
      ],
      wDTypeList: [
        {
          value: 0,
          label: '仓库名称'
        }
      ],
      tableProps: [
        {
          prop: 'yearPhaseName',
          label: '年期',
          minWidth: 200,
          showOverflowtooltip: true
        },
        {
          prop: 'center',
          label: '成本中心名称',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'product',
          label: '产品名称',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'spec',
          label: '规格型号',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'workorderCode',
          label: '工单编号',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'workorderLineNum',
          label: '工单行号',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'supplierCode',
          label: '供应商编码',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'supplier',
          label: '供应商名称',
          minWidth: 150,
          showOverflowtooltip: true
        },
        {
          prop: 'unit',
          label: '基本单位',
          minWidth: 150,
          // filter: (val) => factoryList[val],
          showOverflowtooltip: true
        },
        {
          prop: 'planNum',
          label: '计划产量',
          minWidth: 150,
          // filter: (val) => factoryList[val],
          showOverflowtooltip: true
        },
        {
          prop: 'project',
          label: '成本项目名称',
          minWidth: 150,
          // filter: (val) => factoryList[val],
          showOverflowtooltip: true
        },
        {
          prop: 'material',
          label: '子项物料名称',
          minWidth: 150,
          // filter: (val) => factoryList[val],
          showOverflowtooltip: true
        },
        {
          prop: 'currentTime',
          label: '本期完工',
          minWidth: 150,
          // filter: (val) => factoryList[val],
          showOverflowtooltip: true,
          children: [
            {
              prop: 'finishNum',
              label: '数量',
              minWidth: 150,
              // filter: (val) => factoryList[val],
              showOverflowtooltip: true
            },
            {
              prop: 'unitConsume',
              label: '单耗',
              minWidth: 150,
              // filter: (val) => factoryList[val],
              showOverflowtooltip: true
            },
            {
              prop: 'unitCost',
              label: '单位成本',
              minWidth: 150,
              // filter: (val) => factoryList[val],
              showOverflowtooltip: true
            },
            {
              prop: 'cost',
              label: '金额',
              minWidth: 150,
              // filter: (val) => factoryList[val],
              showOverflowtooltip: true
            },
          ]
        },
        {
          prop: 'totalTime',
          label: '累计完工',
          minWidth: 150,
          // filter: (val) => factoryList[val],
          showOverflowtooltip: true,
          children: [
            {
              prop: 'totalFinishNum',
              label: '数量',
              minWidth: 150,
              // filter: (val) => factoryList[val],
              showOverflowtooltip: true
            },
            {
              prop: 'totalUnitConsume',
              label: '单耗',
              minWidth: 150,
              // filter: (val) => factoryList[val],
              showOverflowtooltip: true
            },
            {
              prop: 'totalUnitCost',
              label: '单位成本',
              minWidth: 150,
              // filter: (val) => factoryList[val],
              showOverflowtooltip: true
            },
            {
              prop: 'totalCost',
              label: '金额',
              minWidth: 150,
              // filter: (val) => factoryList[val],
              showOverflowtooltip: true
            },
          ]
        },
      ],
      // timeSelect:'month',
      // startTimeStamp:null, //开始时间
      // endTimeStamp:null, //结束时间
      // date:'凯盛玻璃控股成员企业2024生产数据',
      // reportTime: '',
      // startTimeStamp: '',
      // endTimeStamp: '',
      tableData: [],
      // proLineList: [],
      // all: {}
    };
  },
  computed: {
  },
  watch: {
  },
  created() {
    const currentYear = new Date().getFullYear();
    this.listQuery.start = `${currentYear}01期`;
    this.listQuery.end = `${currentYear}12期`;
  },
  methods: {
    handleChange(value) {
      // console.log('选择的值:', this.selectedValues);
    },
    async getDataList() {
      this.tableData = []
      this.listQuery.yearPhaseStart = this.listQuery.start ? this.listQuery.start.slice(0,6) :undefined
      this.listQuery.yearPhaseEnd = this.listQuery.end ? this.listQuery.end.slice(0, 6) : undefined
      if (this.listQuery.end && this.listQuery.start) {
        if (this.listQuery.end.slice(0, 4) - this.listQuery.start.slice(0, 4) > 10) {
          this.listQuery.end = undefined
          this.listQuery.start = undefined
          this.listQuery.yearPhaseStart = undefined
          this.listQuery.yearPhaseEnd = undefined
          return this.$message({
            message: '起止年份不能超过十年',
            type: 'warning'
          });
        }
        await getCostMainPage(this.listQuery).then(res => {
          if (res.code === 0) {
            // this.tableData = res.data.list
            res.data.list.forEach((item, index) => {
              let obj = {
                in: Math.random().toString().slice(2, 10),
                id:item.id,
                yearPhase: item.yearPhase,
                center: item.center,
                product: item.product,
                spec: item.spec,
                workorderCode: item.workorderCode,
                workorderLineNum: item.workorderLineNum,
                supplierCode: item.supplierCode,
                supplier: item.supplier,
                unit: item.unit,
                planNum: item.planNum,
                finishNum: item.finishNum,
                unitConsume: item.unitConsume,
                unitCost: item.unitCost,
                cost: item.cost,
                totalFinishNum: item.totalFinishNum,
                totalUnitConsume: item.totalUnitConsume,
                totalUnitCost: item.totalUnitCost,
                totalCost: item.totalCost,
                createTime: item.createTime,
                yearPhaseName: item.yearPhaseName,
                project: item.project,
                material: item.material,
                children:[]
              }
              this.tableData.push(obj)
              item.children.forEach((ele, ind) => {
                // for (let i in item.projs) {
                let obj = {
                  in: Math.random().toString().slice(2, 10),
                  id: ele.id,
                  yearPhase: ele.yearPhase,
                  center: ele.center,
                  product: ele.product,
                  spec: ele.spec,
                  workorderCode: ele.workorderCode,
                  workorderLineNum: ele.workorderLineNum,
                  supplierCode: ele.supplierCode,
                  supplier: ele.supplier,
                  unit: ele.unit,
                  planNum: ele.planNum,
                  finishNum: ele.finishNum,
                  unitConsume: ele.unitConsume,
                  unitCost: ele.unitCost,
                  cost: ele.cost,
                  totalFinishNum: ele.totalFinishNum,
                  totalUnitConsume: ele.totalUnitConsume,
                  totalUnitCost: ele.totalUnitCost,
                  totalCost: ele.totalCost,
                  createTime: ele.createTime,
                  yearPhaseName: ele.yearPhaseName,
                  project: ele.project,
                  material: ele.material,
                  children:[]
                }
                this.tableData[index].children.push(obj)
                ele.children?.forEach((i,inde) => {
                  // for (let i in item.projs) {
                  let obj = {
                    in: Math.random().toString().slice(2, 10),
                    id: i.id,
                    yearPhase: i.yearPhase,
                    center: i.center,
                    product: i.product,
                    spec: i.spec,
                    workorderCode: i.workorderCode,
                    workorderLineNum: i.workorderLineNum,
                    supplierCode: i.supplierCode,
                    supplier: i.supplier,
                    unit: i.unit,
                    planNum: i.planNum,
                    finishNum: i.finishNum,
                    unitConsume: i.unitConsume,
                    unitCost: i.unitCost,
                    cost: i.cost,
                    totalFinishNum: i.totalFinishNum,
                    totalUnitConsume: i.totalUnitConsume,
                    totalUnitCost: i.totalUnitCost,
                    totalCost: i.totalCost,
                    createTime: i.createTime,
                    yearPhaseName: i.yearPhaseName,
                    project: i.project,
                    material: i.material,
                  }
                  this.tableData[index].children[ind].children.push(obj)
                  // });
                  // }
                });
                // });
                // }
              });

            });
            console.log(this.tableData);
            this.listQuery.total = res.data.total
          }
        })
      } else {
        return this.$message({
          message: '请选择起止年份和期数',
          type: 'warning'
        });
      }

    },
    buttonClick(val) {
      this.listQuery.reportTime = val.reportTime ? val.reportTime : undefined;
      switch (val.btnName) {
        case 'search':
          this.listQuery.pageNo = 1;
          this.listQuery.pageSize = 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 exportExcel(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>
