<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="企业名称" prop="name">
        <el-select v-model="queryParams.name" style="width: 100%" filterable clearable>
          <el-option
            v-for="item in enterpriseData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年份" prop="year">
        <!-- <el-input
          v-model="queryParams.year"
          placeholder="请输入年份"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-select v-model="queryParams.year" style="width: 100%" filterable clearable>
            <el-option
              v-for="key in yearsOptions"
              :key="key"
              :label="key"
              :value="key"
            >
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="月份" prop="month">
        <!-- <el-input
          v-model="queryParams.month"
          placeholder="请输入月份"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-select v-model="queryParams.month" filterable style="width: 100%" clearable>
            <el-option
              v-for="key in monthSearchOptions"
              :key="key"
              :label="key"
              :value="key"
            >
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input
          v-model="queryParams.unit"
          placeholder="请输入单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="creator">
        <el-input
          v-model="queryParams.creator"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="指数" prop="indexv">
        <el-input
          v-model="queryParams.indexv"
          placeholder="请输入指数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['priceindex:priceindex:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['priceindex:priceindex:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['priceindex:priceindex:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['priceindex:priceindex:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['priceindex:priceindex:import']"
          >导入</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="priceindexList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="企业名称" align="center" prop="name" />
      <el-table-column label="年份" align="center" prop="year" />
      <el-table-column label="月份" align="center" prop="month" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="创建人" align="center" prop="creator" />
      <el-table-column label="指数" align="center" prop="indexv" />
      <el-table-column
        label="操作"
        align="center"
        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="['priceindex:priceindex:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['priceindex:priceindex:remove']"
            >删除</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"
    />

    <!-- 添加或修改priceindex对话框 -->
    <el-dialog :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="代码" prop="code">
          <el-select v-model="form.code" style="width: 100%" filterable>
            <el-option
              v-for="item in industryData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <!-- <el-input v-model="form.code" placeholder="请输入代码" /> -->
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-select v-model="form.name" style="width: 100%" filterable>
            <el-option
              v-for="item in enterpriseData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <!-- <el-input v-model="form.name" type="textarea" placeholder="请输入内容" /> -->
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-select v-model="form.year" style="width: 100%" filterable>
            <el-option
              v-for="key in yearsOptions"
              :key="key"
              :label="key"
              :value="key"
            >
            </el-option>
          </el-select>
          <!-- <el-input v-model="form.year" placeholder="请输入年份" /> -->
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-select v-model="form.month" filterable style="width: 100%">
            <el-option
              v-for="key in monthOptions"
              :key="key"
              :label="key"
              :value="key"
            >
            </el-option>
          </el-select>
          <!-- <el-input v-model="form.month" placeholder="请输入月份" /> -->
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="指数" prop="indexv">
          <el-input v-model.number="form.indexv" placeholder="请输入指数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link
            type="primary"
            style="font-size: 12px"
            @click="importTemplate"
            >点击此处下载文件上传模板</el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </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>
  </div>
</template>

<script>
import {
  listPriceindex,
  getPriceindex,
  delPriceindex,
  addPriceindex,
  updatePriceindex,
} from "@/api/priceindex/priceindex";
import { getToken } from "@/utils/auth";
// 获取行业
import { listAllIndustry } from "@/api/industry/industry";
// 获取企业
import { listAllEnterprise } from "@/api/enterprise/enterprise";
// 获取年度数据
import { getYearData } from "@/api/home";
export default {
  name: "Priceindex",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // priceindex表格数据
      priceindexList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        month: null,
        year: null,
        unit: null,
        creator: null,
        indexv: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: { required: true, message: "请选择行业", trigger: "blur" },
        name: { required: true, message: "请选择企业", trigger: "blur" },
        month: { required: true, message: "请填写月份", trigger: "blur" },
        year: { required: true, message: "请填写年份", trigger: "blur" },
        unit: { required: true, message: "请填写单位", trigger: "blur" },
        creator: { required: true, message: "请填写创建人", trigger: "blur" },
        indexv: { required: true, message: "请填写指数", trigger: "blur" },
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/priceindex/priceindex/importData",
      },
      industryData: [],
      enterpriseData: [],
      yearsOptions: [],
      monthMap: new Map(),
    };
  },
  created() {
    this.getList();
    this.initSelectData();
  },
  computed: {
    monthOptions() {
      const options = this.form.year ? this.monthMap.get(this.form.year) : [];
      return options || []; // 以防得到 undefined
    },
    monthSearchOptions() {
      const options = this.queryParams.year ? this.monthMap.get(this.queryParams.year) : [];
      return options || []; // 以防得到 undefined
    },
  },
  methods: {
    /** 查询priceindex列表 */
    getList() {
      this.loading = true;
      listPriceindex(this.queryParams).then((response) => {
        this.priceindexList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    initSelectData() {
      // 获取行业数据
      listAllIndustry().then((response) => {
        this.industryData = response.rows.map((item) => {
          return {
            value: item.code,
            label: item.code + item.industryName,
            name: item.industryName,
          };
        });
      });
      // 获取企业数据
      listAllEnterprise().then((response) => {
        this.enterpriseData = response.rows.map((item) => {
          return {
            value: item.enterpriseName,
            label: item.enterpriseName,
          };
        });
      });
      // 获取年度数据
      getYearData().then((response) => {
        this.yearsOptions = response.rows[0].years;
        this.monthMap = this.generateMonthlyData(this.yearsOptions);
      });
    },
    generateMonthlyData(years) {
      const currentYear = new Date().getFullYear();
      const currentMonth = new Date().getMonth() + 1;
      const monthlyData = new Map();
      years.forEach((year) => {
        if (year === currentYear) {
          // 当前年份，判断当前月份
          const months = Array.from({ length: currentMonth }, (_, i) => i + 1);
          monthlyData.set(year, months); // 设置当前年份的已过月份
        } else if (year < currentYear) {
          // 过去的年份包含所有12个月
          monthlyData.set(year, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
        } else {
          // 未来的年份
          monthlyData.set(year, []);
        }
      });

      return monthlyData;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        code: null,
        name: null,
        month: null,
        year: null,
        unit: null,
        creator: null,
        indexv: 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 = "添加数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPriceindex(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      // console.log(this.form)
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.industryName = this.industryData.filter(
            (item) => item.value === this.form.code
          )[0].name;
          // console.log(this.form)
          if (this.form.id != null) {
            updatePriceindex(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPriceindex(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function () {
          return delPriceindex(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "priceindex/priceindex/export",
        {
          ...this.queryParams,
        },
        `priceindex_${new Date().getTime()}.xlsx`
      );
    },
    handleImport() {
      this.upload.title = "数据导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "priceindex/priceindex/importTemplate",
        {},
        `priceindex_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    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, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
