<!--
 * @Author: zhp
 * @Date: 2023-12-12 13:45:25
 * @LastEditTime: 2024-03-12 11:14:04
 * @LastEditors: zhp
 * @Description:
-->
<template>
  <div class="app-container">
    <el-form :inline="true" :model="dataForm" class="demo-form-inline">
      <el-form-item>
        <el-date-picker v-model="monthValue" type="monthrange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" clearable :picker-options="pickerOptions" size="small" style='width:350px;'
          @change="timeSelect">
        </el-date-picker>
      </el-form-item>
      <el-button type="primary" @click="getDataList()">查询</el-button>
      <el-button v-if="this.$auth.hasPermi('report:glass-month:export')" type="primary" size="small" plain
        @click="handleExport">导出</el-button>
    </el-form>
    <el-row style="float: right; margin-bottom: 5px">
      <el-button size="small" @click="editDataList()">编辑</el-button>
      <el-button size="small" v-if="isSave" @click="saveDataList()">保存</el-button>
    </el-row>
    <el-table :data="list" style="width: 100%" :header-cell-style="{
      background: '#F2F4F9',
      color: '#606266'
    }">
      <el-table-column :label="'许昌安彩月成品生产汇总' + '(' + timeTips + ')'" align="center">
        <el-table-column prop="lineId" label="生产线" align="center">
          <template slot-scope="scope">
            <el-input v-if="!disabled" v-model="scope.row.lineName" :disabled="disabled"></el-input>
            <span v-else>{{ scope.row.lineName }} </span>
          </template>
        </el-table-column>
        <el-table-column label="投入数㎡" align="center">
          <el-table-column prop="inputNow" label="本月" align="center">
            <template slot-scope="scope">
              <el-input v-if="!disabled" v-model="scope.row.inputNow" :disabled="disabled"></el-input>
              <span v-else>{{ scope.row.inputNow }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="inputHis" label="上月" align="center">
            <template slot-scope="scope">
              <el-input v-if="!disabled" v-model="scope.row.inputHis" :disabled="disabled"></el-input>
              <span v-else>{{ scope.row.inputHis }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="inputTrend" label="增减" align="center">
            <template slot-scope="scope">
              <el-input v-if="!disabled" v-model="scope.row.inputTrend" :disabled="disabled"></el-input>
              <span v-else>{{ scope.row.inputTrend ? scope.row.inputTrend + '%' : undefined }} </span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="完成良品产量" align="center">
          <el-table-column prop="goodProductNow" label="本月" align="center">
            <template slot-scope="scope">
              <el-input v-if="!disabled" v-model="scope.row.goodProductNow" :disabled="disabled">
              </el-input>
              <span v-else>{{ scope.row.goodProductNow }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="goodProductHis" label="上月" align="center">
            <template slot-scope="scope">
              <el-input v-if="!disabled" v-model="scope.row.goodProductHis" :disabled="disabled">
              </el-input>
              <span v-else>{{ scope.row.goodProductHis }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="goodProductTrend" label="增减" align="center">
            <template slot-scope="scope">
              <el-input v-if="!disabled" v-model="scope.row.goodProductTrend" :disabled="disabled">
              </el-input>
              <span v-else>{{ scope.row.goodProductTrend ? scope.row.goodProductTrend + '%' : undefined }} </span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="原片漏检率" align="center">
          <el-table-column prop="missCheckNow" label="本月" align="center">
            <template slot-scope="scope">
              <el-input v-if="!disabled" v-model="scope.row.missCheckNow" :disabled="disabled"></el-input>
              <span v-else>{{ scope.row.missCheckNow }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="missCheckHis" label="上月" align="center">
            <template slot-scope="scope">
              <el-input v-if="!disabled" v-model="scope.row.missCheckHis" :disabled="disabled"></el-input>
              <span v-else>{{ scope.row.missCheckHis }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="missCheckTrend" label="增减" align="center">
            <template slot-scope="scope">
              <el-input v-if="!disabled" v-model="scope.row.missCheckTrend" :disabled="disabled">
              </el-input>
              <span v-else>{{ scope.row.missCheckTrend ? scope.row.missCheckTrend +'%' : undefined }} </span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="综合良品率" align="center">
          <el-table-column prop="goodProductPassNow" label="本月" align="center">
            <template slot-scope="scope">
              <el-input v-if="!disabled" v-model="scope.row.goodProductPassNow" :disabled="disabled">
              </el-input>
              <span v-else>{{ scope.row.goodProductPassNow }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="goodProductPassHis" label="上月" align="center">
            <template slot-scope="scope">
              <el-input v-if="!disabled" v-model="scope.row.goodProductPassHis" :disabled="disabled">
              </el-input>
              <span v-else>{{ scope.row.goodProductPassHis }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="goodProductPassTrend" label="增减" align="center">
            <template slot-scope="scope">
              <el-input v-if="!disabled" v-model="scope.row.goodProductPassTrend" :disabled="disabled">
              </el-input>
              <span v-else>{{ scope.row.goodProductPassTrend ? scope.row.goodProductPassTrend + '%' :undefined }}
              </span>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table-column>
      <div style="height: 50px;" class="remark" slot="append">
        <el-input placeholder="备注" v-if="!disabled" v-model="remark" :disabled="disabled">
        </el-input>
        <span v-else>{{ remark }} </span>
      </div>
    </el-table>
    <!-- 搜索工作栏 -->
    <!-- <SearchBar :formConfigs="searchBarFormConfig" ref="search-bar" @headBtnClick="handleSearchBarBtnClick" /> -->

    <!-- 列表 -->
    <!-- <base-table :table-props="tableProps" :page="1" :limit="10" :summary-method="getSummaries" show-summary
      :table-data="list">
    </base-table> -->
    <!-- 分页组件 -->
    <!-- <pagination
			v-show="total > 0"
			:total="total"
			:page.sync="queryParams.pageNo"
			:limit.sync="queryParams.pageSize"
			@pagination="getList" /> -->
  </div>
</template>

<script>
import {
  getProductionDataList,
  updateProductionDataList,
  updateSumProductionDataList,
  exportProductExcel
} from '@/api/report/production';
// import Editor from '@/components/Editor';
import moment from 'moment';
// import DialogForm from './dialogForm.vue';
import { getCorePLList } from '@/api/base/coreProductionLine'

// import basicPageMixin from '@/mixins/lb/basicPageMixin';
const tableProps = [
    {
      // width: 128,
    prop: 'lineId',
    label: '生产线',
    },
    {
      // width: 128,
      prop: '',
      label: '投入数㎡',
      align: 'center',
      children: [
        {
          prop: 'inputNow',
          label: '本月'
        },
        {
          prop: 'inputHis',
          label: '上月'
        },
        {
          prop: 'inputTrend',
          label: '增减'
        }
      ]
    },
  {
    // width: 128,
    prop: '',
    label: '完成良品产量',
    align: 'center',
    children: [
      {
        prop: 'goodProductNow',
        label: '本月'
      },
      {
        prop: 'goodProductHis',
        label: '上月'
      },
      {
        prop: 'goodProductTrend',
        label: '增减'
      }
    ]
  },
  {
    // width: 128,
    prop: '',
    label: '原片漏检率',
    align: 'center',
    children: [
      {
        prop: 'missCheckNow',
        label: '本月'
      },
      {
        prop: 'missCheckHis',
        label: '上月'
      },
      {
        prop: 'missCheckTrend',
        label: '增月'
      }
    ]
  },
  {
    // width: 128,
    prop: '',
    label: '综合良品率',
    align: 'center',
    children: [
      {
        prop: 'goodProductPassNow',
        label: '本月'
      },
      {
        prop: 'goodProductPassHis',
        label: '上月'
      },
      {
        prop: 'goodProductPassTrend',
        label: '增减'
      }
    ]
  },
  ];
export default {
  name: 'statisticalData',
	// components: {
	// 	DialogForm,
	// },
	// mixins: [basicPageMixin],
	data() {
    return {
      list: [],
      remark: '',
      monthValue:[],
      // dynamicProps: [],
      tableProps,
      urlOptions: {
        exportURL: exportProductExcel
      },
      isSave:false,
      disabled: true,
      sumArr: [],
      timeTips:'',
      searchBarFormConfig: [
        // {
        //   type: 'select',
        //   label: '工单名称',
        //   placeholder: '请选择工单名称',
        //   param: 'workOrderIdList',
        //   selectOptions: [],
        //   multiple: true,
        //   labelField: 'name',
        //   valueField: 'id',
        //   defaultSelect: []
        // },
				// {
				// 	type: 'select',
				// 	label: '产品',
        //   placeholder: '请选择产品',
        //   param: 'productionId',
				// 	selectOptions: [],
				// },
				// {
				// 	type: 'input',
				// 	label: '检测内容',
				// 	placeholder: '请输入检测内容',
				// 	param: 'inspectionDetContent',
				// },
				{
					type: 'datePicker',
					label: '时间段',
					dateType: 'daterange', // datetimerange
					// format: 'yyyy-MM-dd HH:mm:ss',
          format: 'yyyy-MM-dd HH:mm:ss',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
					rangeSeparator: '-',
					startPlaceholder: '开始日期',
					endPlaceholder: '结束日期',
					defaultTime: ['00:00:00', '23:59:59'],
					param: 'checkTime',
					// width: 350,
				},
				{
					type: 'button',
					btnName: '查询',
					name: 'search',
					color: 'primary',
				},
				// {
				// 	type: this.$auth.hasPermi(
				// 		'base:quality-inspection-record:create'
				// 	)
				// 		? 'button'
				// 		: '',
				// 	btnName: '新增',
				// 	name: 'add',
				// 	plain: true,
				// 	color: 'success',
				// },
      ],
      pickerOptions: {
        disabledDate(date) {
          return date.getTime() > Date.now()
        }
      },
			// tableBtn: [
			// 	this.$auth.hasPermi('base:quality-inspection-record:update')
			// 		? {
			// 				type: 'edit',
			// 				btnName: '修改',
			// 		  }
			// 		: undefined,
      //   this.$auth.hasPermi('base:quality-inspection-record:delete')
			// 		? {
			// 				type: 'delete',
			// 				btnName: '删除',
			// 		  }
			// 		: undefined,
			// ].filter((v) => v),
			// tableProps: [
			// 	{
			// 		prop: 'createTime',
			// 		label: '添加时间',
			// 		fixed: true,
			// 		width: 180,
			// 		filter: (val) => moment(val).format('yyyy-MM-DD HH:mm:ss'),
			// 	},
			// 	{
			// 		// width: 128,
			// 		prop: 'inspectionDetContent',
			// 		label: '检测内容',
			// 	},
			// 	{
			// 		// width: 128,
			// 		prop: 'lineName',
			// 		label: '产线',
			// 	},
			// 	{
			// 		// width: 128,
			// 		prop: 'checkPerson',
			// 		label: '检测人员',
			// 	},
			// 	{
			// 		// width: 160,
			// 		prop: 'checkTime',
			// 		label: '检测时间',
			// 		filter: (val) =>
			// 			val != null ? moment(val).format('yyyy-MM-DD HH:mm:ss') : '-',
			// 	},
			// 	{
			// 		width: 90,
			// 		prop: 'source',
			// 		label: '来源',
			// 		filter: (val) => ['未知', '手动', '自动'][val],
			// 	},
			// ],
      // 搜索框需要的 keys, 与上面 queryParams 的除 pageNo, pageSize 之外的 key 一一对应

			// searchBarKeys: ['inspectionDetContent', 'checkTime', 'productionLineId'],
			// form: {
			// 	id: undefined,
			// 	inspectionDetId: undefined,
			// 	inspectionDetContent: undefined,
			// 	productionLineId: undefined,
			// 	sectionId: undefined,
			// 	checkPerson: undefined,
			// 	checkTime: undefined,
			// 	source: undefined,
			// 	explainText: undefined,
			// 	remark: undefined,
			// },
			// 查询参数
      dataForm: {
        // workOrderIdList:undefined,
        // productionId: undefined,
        // startTime: undefined,
        // endTime: undefined,
        reportTime: [],
        reportType:4,
				// productionLineId: null,
			},
		};
  },
  created() {
    this.getCurrentMonthFirst()
    this.getCurrentMonthLast()
		// this.getProductLineList();
  },
  mounted() {
    // if (this.$route.params.startTime && this.$route.params.endTime) {
    //   this.searchBarFormConfig[0].defaultSelect = [
    //     this.$route.params.startTime,
    //     this.$route.params.endTime,
    //   ];
    //   this.queryParams.param = {};
    //   this.$set(
    //     this.queryParams.param,
    //     'startTime',
    //     this.$route.params.startTime
    //   );
    //   this.$set(this.queryParams.param, 'endTime', this.$route.params.endTime);
    // } else {
    //   this.searchBarFormConfig[0].defaultSelect = [];
    // }

    this.getDataList()
    this.getDict()
  },
  methods: {
    async getDict() {
      // 产线列表
      const res = await getCorePLList();
      this.proLineList = res.data;
    },
    handleExport() {
      // 处理查询参数
      let params = { ...this.dataForm };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有数据项?').then(() => {
        this.exportLoading = true;
        return this.urlOptions.exportURL(params);
      }).then(response => {
        this.$download.excel(response, '成品生产月报.xls');
        this.exportLoading = false;
      }).catch(() => { });
    },
    getCurrentMonthFirst() {
      const date = new Date();
      date.setDate(1)
      // date.setHours(7, 0, 1)
      this.monthValue[0] = moment(date).format('YYYY-MM-DD')
      console.log(date)
      // console.log(date.valueOf());
    },
    getCurrentMonthLast() {
      const date = new Date();
      const currentMonth = date.getMonth();
      const nextMonth = currentMonth + 1;
      const nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      const oneDay = 24 * 60 * 60 * 1000;
      this.monthValue[1] = new Date(nextMonthFirstDay - oneDay)
    },
    timeSelect() {
      // switch (this.queryParams.timeDim) {
        // case '1':
        //   if (this.timeValue[1] - this.timeValue[0] > 7 * 24 * 3600000) {
        //     this.$modal.msgError('最大时间范围为7天，请重新选择')
        //     this.timeValue = []
        //   }
        //   break
      // case '2':
      console.log(this.monthValue[1],this.monthValue[0]);
      if (this.monthValue[1] - this.monthValue[0] > 2629800000) {
        this.$modal.msgError('最大时间范围为1个月，请重新选择')// 同理上面
        this.monthValue = []
      }
        //   break
        // case '4':
        //   if (this.monthValue[1] - this.monthValue[0] > 729 * 24 * 3600000) {
        //     this.$modal.msgError('最大时间范围为24个月，请重新选择')// 同理上面
        //     this.monthValue = []
        //   }
        //   break
        // default:
    },
    transformTime(timeStamp) {// 本月最后一天
      let year = moment(timeStamp).format('YYYY')
      let month = moment(timeStamp).format('MM')
      let newData = moment(new Date(year, month, 0)).format('YYYY-MM-DD') + ' 23:59:59'
      let value = newData
      console.log(value);
      return value
    },
    transformStartTime(timeStamp) {// 本月最后一天
      let year = moment(timeStamp).format('YYYY')
      let month = moment(timeStamp).format('MM')
      let newData = moment(new Date(year, month, 1)).format('YYYY-MM-DD') + ' 23:59:59'
      let value = newData
      console.log(value);
      return value
    },
    // selectTime() {
    //   switch (this.queryParams.type) {
    //     case 1:
    //       this.queryParams.searchTime = this.monthValue
    //       break;
    //     case 2:
    //       this.queryParams.searchTime = this.weekValue
    //       break;
    //     default:
    //       this.queryParams.searchTime = this.dateValue
    //   }
    // },
    editDataList() {
      this.disabled = false
      this.isSave = true
    },
    async saveDataList() {
      let obj = {}
      this.list.forEach((ele, index) => {
        if (ele.det === false) {
          this.list[index].lineId = ''
          this.list[index].remark = this.remark
          obj = ele
          this.list.splice(index,1)
        }
      })
      let updateArr = this.list
      // console.log(JSON.stringify(updateArr[1]))
      const result = await Promise.all([
        await updateSumProductionDataList(obj),
        await updateProductionDataList(updateArr),
      ])
      console.log(result);
      if (result[0].data == true && result[1].data == true) {
        // console.log(res)
        this.disabled = true
        this.isSave = false
        this.getDataList()
      }
    },
    async getDataList() {
      if (this.monthValue.length > 0) {
        console.log(this.monthValue)
        this.dataForm.reportTime[0] = moment(this.monthValue[0]).format('YYYY-MM-DD') + ' 07:00:01'
        // this.queryParams.startTime = this.monthValue[0]
        this.dataForm.reportTime[1] = moment(this.monthValue[1]).format('YYYY-MM-DD') + ' 07:00:00'
        this.timeTips = moment(this.monthValue[0]).format('YYYY-MM-DD') + ' - ' + moment(this.monthValue[1]).format('YYYY-MM-DD')
        console.log(this.timeTips);
      } else {
        // this.$modal.msgError('月范围不能为空')
        // return false
      }

      console.log(this.dataForm);
      const res = await this.$axios({
        url: '/base/report-auto-production/page',
        method: 'get',
        params: this.dataForm
      })
      console.log(res)
      // let sum = undefined
      // res.data.list.forEach((ele, index) => {
      //   if (ele.det === false) {
      //    sum = res.data.list.splice(index, 1)
      //   }
      // })
      res.data.list.forEach((ele,index) => {
        if (ele.det === false) {
          res.data.list[index].lineName = '合计'
          this.remark = res.data.list[index].remark
        }
      })
      res.data.list.forEach(item => {
        this.proLineList.forEach(it => {
          if (item.lineId === it.id) {
            console.log(item)
            item.lineName = it.name
          }
        })
      })

      this.list = res.data.list
      // this.list = res.data.list
    },
	},
};
</script>
