<template>
    <div class="app-container-QZFT">
        <div id="QZFTChart" class="tab-Chart"></div>
      <el-col style="background-color: #1890ff;" >
        <div class="block">
          <el-date-picker
            v-model="searchFormField.year"
            align="right"
            type="year"
            :placeholder="$t('请选择') + $t('年份')"
            :picker-options="pickerOptions"
            @change="changeList"
            style="width: 100px; margin: 1px 10px 1px 10px">
          </el-date-picker>
          <span style="color: white">BTX Output</span>
        </div>

      </el-col>

      <el-table v-loading="loading" :data="monthplanList" @selection-change="handleSelectionChange" height="200" border style="width: 100%">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column :label="$t('年份')" align="center" prop="year" :show-overflow-tooltip="true"/>
        <el-table-column label="BTX" align="center" prop="btx" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('一月')" align="center" prop="jan" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('二月')" align="center" prop="feb" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('三月')" align="center" prop="mar" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('四月')" align="center" prop="apr" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('五月')" align="center" prop="may" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('六月')" align="center" prop="jun" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('七月')" align="center" prop="jul" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('八月')" align="center" prop="aug" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('九月')" align="center" prop="sep" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('十月')" align="center" prop="oct" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('十一月')" align="center" prop="nov" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('十二月')" align="center" prop="dec" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('操作')" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['production:monthplan:edit']"
            >{{ $t('修改') }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['production:monthplan:remove']"
            >{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改生产计划及月报对话框 -->
      <el-dialog  :close-on-click-modal="false" v-dialogDrag :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="BTX" prop="btx">
            <el-input v-model="form.btx" :placeholder="$t('请输入') + BTX" />
          </el-form-item>
          <el-form-item :label="$t('一月')" prop="jan">
            <el-input v-model="form.jan" onkeyup="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('请输入') + $t('一月')" />
          </el-form-item>
          <el-form-item :label="$t('二月')" prop="feb">
            <el-input v-model="form.feb" onkeyup="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('请输入') + $t('二月')" />
          </el-form-item>
          <el-form-item :label="$t('三月')" prop="mar">
            <el-input v-model="form.mar" onkeyup="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('请输入') + $t('三月')" />
          </el-form-item>
          <el-form-item :label="$t('四月')" prop="apr">
            <el-input v-model="form.apr" onkeyup="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('请输入') + $t('四月')" />
          </el-form-item>
          <el-form-item :label="$t('五月')" prop="may">
            <el-input v-model="form.may" onkeyup="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('请输入') + $t('五月')" />
          </el-form-item>
          <el-form-item :label="$t('六月')" prop="jun">
            <el-input v-model="form.jun" onkeyup="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('请输入') + $t('六月')" />
          </el-form-item>
          <el-form-item :label="$t('七月')" prop="jul">
            <el-input v-model="form.jul" onkeyup="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('请输入') + $t('七月')" />
          </el-form-item>
          <el-form-item :label="$t('八月')" prop="aug">
            <el-input v-model="form.aug" onkeyup="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('请输入') + $t('八月')" />
          </el-form-item>
          <el-form-item :label="$t('九月')" prop="sep">
            <el-input v-model="form.sep" onkeyup="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('请输入') + $t('九月')" />
          </el-form-item>
          <el-form-item :label="$t('十月')" prop="oct">
            <el-input v-model="form.oct" onkeyup="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('请输入') + $t('十月')" />
          </el-form-item>
          <el-form-item :label="$t('十一月')" prop="nov">
            <el-input v-model="form.nov" onkeyup="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('请输入') + $t('十一月')" />
          </el-form-item>
          <el-form-item :label="$t('十二月')" prop="dec">
            <el-input v-model="form.dec" onkeyup="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('请输入') + $t('十二月')" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">{{ $t('确 定') }}</el-button>
          <el-button @click="cancel">{{ $t('取 消') }}</el-button>
        </div>
      </el-dialog>

      <!-- 用户导入对话框 -->
      <el-dialog  :close-on-click-modal="false" v-dialogDrag :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 + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            {{ $t('将文件拖到此处，或') }}
            <em>{{ $t('点击上传') }}</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            <!--<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据-->
            <el-link type="info" style="font-size:12px" @click="importTemplate">{{ $t('下载模板') }}</el-link>
          </div>
          <div class="el-upload__tip" style="color:red" slot="tip">{{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}</div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">{{ $t('确 定') }}</el-button>
          <el-button @click="upload.open = false">{{ $t('取 消') }}</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
  import {
    addMonthplan,
    delMonthplan,
    exportMonthplan,
    getMonthplan,
    importTemplate,
    listMonthplan,
    updateMonthplan
  } from "@/api/production/monthplan";
  import {treeselect} from "@/api/system/dept";
  import {getToken} from "@/utils/auth";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import resize from "@/views/dashboard/mixins/resize";

  export default {
    mixins: [resize],
    name: "monthplanQZFT",
    components: { Treeselect },
    props: {
      width: {
        type: String,
        default: '100%'
      },
    },
    data() {
      return {
        chart: null,
        // 选择当前年份及之前的年份
        pickerOptions: {
          disabledDate: (time) => {
            return time.getTime() > Date.now() + 31536000000;
          }
        },
        // 获取屏幕宽度
        screenWidth: document.body.clientWidth,
        // 获取当前年份
        searchFormField: {
          year: this.getNowTime(),
        },
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 生产计划及月报表格数据
        monthplanList: [],
        //显示表格数据
        chartsList1: [],
        chartsList2: [],
        chartsList3: [],
        // 弹出层标题
        title: "",
        // 部门树选项
        deptOptions: undefined,
        // 是否显示弹出层
        open: false,
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/production/monthplan/importData"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          plantCode: null,
          year: null,
          ethylene: null,
          btx: null,
          kpi: null,
          jan: null,
          feb: null,
          mar: null,
          apr: null,
          may: null,
          jun: null,
          jul: null,
          aug: null,
          sep: null,
          oct: null,
          nov: null,
          dec: null,
          ytd: null,
          target: null,
          sort: null,
          item: 2,
          createrCode: null,
          createdate: null,
          updaterCode: null,
          updatedate: null,
          deptId: null,
          remarks: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          plantCode: [
            { required: true, message: this.$t('装置名称') + this.$t('不能为空'), trigger: "blur" }
          ],
          deptCode: [
            { required: true, message: this.$t('部门编号') + this.$t('不能为空'), trigger: "blur" }
          ],
        }
      };
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val);
      }
    },
    // beforeDestroy() {
    //   if (!this.chart) {
    //     return
    //   }
    //   this.chart.dispose()
    //   this.chart = null
    // },
    created() {
      this.getList();
      this.getTreeselect();
    },
    mounted(){
      this.queryParams.year = this.searchFormField.year;
    },
    methods: {
      /** 获取当前年份 */
      getNowTime() {
        var now = new Date();
        var year = now.getFullYear(); //得到年份
        var defaultDate = `${year}`;
        defaultDate = `${2020}`
        return defaultDate;
        this.$set(this.searchFormField, "year", defaultDate);
      },
      /** 图表 */
      drawLine(){
        // 基于准备好的dom，初始化echarts实例
        this.chart = this.echarts.init(document.getElementById('QZFTChart'))
        // 绘制图表
        this.chart.setOption({
          color: ['#93c555', '#5f6694', '#2f4554'],
          /* 周围边距 */
          grid: {
            left: '3%',
            right: '3%',
            bottom: '1%',
            top: '10%',
            containLabel: true
          },
          /* 标识 */
          legend: {
            data: ['Actul', 'Plan', 'OAE'],
            right: 5,
          },
          /* 坐标轴显示 */
          tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
              type: 'cross',
              label: {
                backgroundColor: '#a0a0a0'
              }
            }
          },
          xAxis: {
            data: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
          },
          yAxis: [
            {
              type: 'value',
              name: 'Unit:(t)',
              min: 0,
              max: 35000,
              interval: 5000,
              axisLabel: {
                formatter: '{value}'
              }
            },
            {
              type: 'value',
              min: 0,
              max: 120,
              interval: 20,
              axisLabel: {
                formatter: '{value} %'
              }
            }
          ],
          series: [
            {
              name: 'Actul',
              type: 'bar',
              barWidth: '40%',
              data: [this.chartsList1.jan, this.chartsList1.feb, this.chartsList1.mar, this.chartsList1.apr, this.chartsList1.may, this.chartsList1.jun, this.chartsList1.jul, this.chartsList1.aug, this.chartsList1.sep, this.chartsList1.oct, this.chartsList1.nov, this.chartsList1.dec]
            },
            {
              name: 'Plan',
              type: 'bar',
              barWidth: '40%',
              data: [this.chartsList2.jan, this.chartsList2.feb, this.chartsList2.mar, this.chartsList2.apr, this.chartsList2.may, this.chartsList2.jun, this.chartsList2.jul, this.chartsList2.aug, this.chartsList2.sep, this.chartsList2.oct, this.chartsList2.nov, this.chartsList2.dec]
            },
            {
              name: 'OAE',
              type: 'line',
              yAxisIndex: 1,
              data: [this.chartsList3.jan, this.chartsList3.feb, this.chartsList3.mar, this.chartsList3.apr, this.chartsList3.may, this.chartsList3.jun, this.chartsList3.jul, this.chartsList3.aug, this.chartsList3.sep, this.chartsList3.oct, this.chartsList3.nov, this.chartsList3.dec]
            }
          ]
        });
      },
      /** 查询生产计划及月报列表 */
      getList() {
        this.loading = true;
        listMonthplan(this.queryParams).then(response => {
          this.monthplanList = response.rows;
          this.chartsList1 = response.rows[0];
          this.chartsList2 = response.rows[1];
          this.chartsList3 = response.rows[2];
          this.drawLine()
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 根据选择年份更新列表 */
      changeList(selVal) {
        this.queryParams.year = selVal.getFullYear();
        this.getList()
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          plantCode: null,
          year: null,
          ethylene: null,
          btx: null,
          kpi: null,
          jan: null,
          feb: null,
          mar: null,
          apr: null,
          may: null,
          jun: null,
          jul: null,
          aug: null,
          sep: null,
          oct: null,
          nov: null,
          dec: null,
          ytd: null,
          target: null,
          sort: null,
          item: 2,
          createrCode: null,
          createdate: null,
          updaterCode: null,
          updatedate: null,
          deptId: null,
          remarks: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = this.$t('新增') + " " + this.$t('生产计划及月报');
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getMonthplan(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = this.$t('修改') + this.$t('生产计划及月报');
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateMonthplan(this.form).then(response => {
                this.msgSuccess(this.$t('修改成功'));
                this.open = false;
                this.getList();
              });
            } else {
              addMonthplan(this.form).then(response => {
                this.msgSuccess(this.$t('新增成功'));
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm(this.$t('是否确认删除生产计划及月报编号为"') + ids + this.$t('"的数据项?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: "warning"
        }).then(function() {
          return delMonthplan(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess(this.$t('删除成功'));
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm(this.$t('是否确认导出所有生产计划及月报数据项?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: "warning"
        }).then(function() {
          return exportMonthplan(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = this.$t('用户导入');
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        importTemplate().then(response => {
          this.download(response.msg);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }
    }
  }
</script>

<style scoped>
.QZFTChart {
  width: 100%;
  height: 400px;
}
</style>
