<template>
  <el-container>
    <el-header v-if="isSearch">
      <el-form style="margin: 10px 0" :inline="true">
        <el-form-item label="项目内容：">
          <el-input v-model="planName" placeholder="请输入项目内容" />
        </el-form-item>
        <el-form-item label="演习年份：">
          <el-select
            v-model="planYear"
            style="width: 200px"
            placeholder="请选择年度"
            @change="getChange"
          >
            <el-option
              v-for="(item, index) in yearList"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-search"
            @click="getList"
          >
            搜索
          </el-button>
          <el-button class="commonBtn" icon="el-icon-refresh" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <el-main>
      <div class="headerTop">
        <div>
          <el-button type="primary" class="el-icon-plus" @click="add">
            导入</el-button
          >
        </div>
        <div>
          <right-toolbar :showSearch.sync="isSearch" @queryTable="getList" ></right-toolbar>
        </div>
      </div>
      <el-table
        height="calc(100% - 200px)"
        :data="list"
        :row-style="{ height: '0px' }"
        :header-cell-style="{ 'text-align': 'center', padding: '0px' }"
        :cell-style="{ 'text-align': 'center', padding: '2px' }"
        style="width: 100%"
      >
        <el-table-column label="序号" align="center">
          <template slot-scope="scope">
            <span> {{ (pageNum - 1) * pageSize + (scope.$index + 1) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="项目内容" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.planName || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划年度" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.planYear || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划月份" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.planMonth || "-" }}</span>
          </template>
        </el-table-column>

        <el-table-column label="负责人" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.directorBy || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="完成人" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.finishBy || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="完成时间" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.finishTime || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="300">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="del(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        @pagination="getList"
      />
    </el-main>
    <el-dialog
      v-loading="loading"
      :visible.sync="addAnnualDrill"
      width="500px"
      title="导入预案"
      :before-close="handleClose"
      element-loading-text="上传中，请稍候..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.4)"
    >
      <div style="width: 100%; text-align: left">
        <div class="container">
          <div class="block">
            <span style="margin-left: 60px">年度：</span>
            <el-date-picker
              v-model="year"
              style="width: 200px"
              align="center"
              type="year"
              :editable="false"
              :picker-options="option"
              :clearable="false"
              placeholder="选择年份"
              @change="changeYear(year)"
            />
          </div>
          <div class="block" style="margin-top: 10px">
            <span style="margin-left: 46px">负责人：</span>
            <!-- <el-select
              style="width: 200px"
              v-model="directorBy"
              clearable
              placeholder="请选择负责人"
            >
              <el-option
                v-for="item in userOption"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              >
              </el-option>
            </el-select> -->
            <el-cascader
              v-model="directorBy"
              style="width: 200px"
              :options="userOption"
              :show-all-levels="false"
              :props="props"
              clearable
            ></el-cascader>
          </div>
        </div>
      </div>
      <div
        style="
          width: 100%;
          display: flex;
          justify-content: left;
          align-items: center;
          margin-top: 20px;
          position: relative;
        "
      >
        <span style="margin: 10px 0 0 60px">附件：</span>
        <el-upload
          ref="upload"
          style="
            position: absolute;
            left: 100px;
            top: 0;
            width: 200px;
            padding: 10px;
          "
          action=""
          :multiple="true"
          accept=".xls, .xlsx"
          :auto-upload="true"
          :limit="1"
          :file-list="fileList"
          :http-request="uploadHttpRequest"
          :on-success="handleSuccess"
          :on-change="handleChange"
        >
          点击上传
        </el-upload>
        <el-link
            type="primary"
            :underline="false"
            style="
            margin-left: 20px;
            color: rgb(2, 154, 223);
            position: absolute;
            left: 300px;
            top: 10px;
          "
            @click="derive"
            >下载模板</el-link
          >
          <!-- <a href="./static/upload/年度演习计划模板.xlsx"  style="
            margin-left: 20px;
            color: rgb(2, 154, 223);
            position: absolute;
            left: 300px;
            top: 10px;
          ">下载模板</a> -->
      </div>
      <el-row style="text-align: center; margin-top: 60px">
        <el-button type="primary" @click="submit"> 提交 </el-button>
        <el-button @click="cancel"> 取消 </el-button>
      </el-row>
    </el-dialog>
  </el-container>
</template>

<script>
import { getYearList, emergency, removeYear, allList, deptUsers, getDeptUserTree } from "@/api/emergencies";
export default {
  name: "RuoyiAllocation",

  data() {
    return {
      props: { multiple: false, emitPath: false },
      planName: "",
      addAlert: false,
      isSearch: true,
      pageNum: 1,
      pageSize: 10,
      directorBy: "",
      total: 1,
      planYear: "",
      list: [],
      userOption: [],
      loading: false,
      yearList: [
        2000, 2001, 2002, 2003, 2004, 2005, 2006, 2006, 2008, 2009, 2010, 2011,
        2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023,
        2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035,
        2036, 2037, 2038, 2039, 2040,
      ],
      typeList: [],
      drillType: "",
      addAnnualDrill: false,
      fileList: [],
      year: "",
      // 年度限制
      option: {
        disabledDate: (time) =>
          time.getTime() < Date.now() - 1 * 24 * 3600 * 1000,
      },
    };
  },

  mounted() {
    this.getList();
    allList().then((res) => {
      if (res.code === 200) {
        console.log(res.data);
        this.typeList = res.data;
      }
    });
    getDeptUserTree().then((res) => {
      console.log(res)
      if (res.code === 200) {
        this.userOption = this.getUser(res.data);
      }
    });
  },

  methods: {
    getUsers(data) {
      return data.map((item) => {
        return { label: item.nickName, value: item.userId };
      });
    },
    getUser(data) {
      return data.map((item) => {
        if (item.children && item.children.length && !item.sysUsers) {
          return {
            label: item.label,
            value: item.id + "d",
            children: this.getUser(item.children),
          };
        }
        if (item.children && item.children.length && item.sysUsers) {
          return {
            label: item.label,
            value: item.id + "d",
            children: [
              ...this.getUser(item.children),
              ...this.getUsers(item.sysUsers),
            ],
          };
        }
        if (!(item.children && item.children.length) && item.sysUsers) {
          return {
            label: item.label,
            value: item.id + "d",
            children: this.getUsers(item.sysUsers),
          };
        }
        if (!(item.children && item.children.length) && !item.sysUsers) {
          return {
            label: item.label,
            value: item.id + "d",
            children: [],
          };
        }
        return { label: item.label, value: item.id + "d" };
      });
    },
    // 文件上传提交
    submit() {
      console.log(this.directorBy)
      if (this.year === "") {
        this.$message.warning("请选择年度");
        return;
      }
      if (this.directorBy === "") {
        this.$message.warning("请选择负责人");
        return;
      }
      if (this.fileList.length === 0) {
        this.$message.warning("请上传文件");
        return;
      }
      this.loading = true;
      const formData = new FormData();
      formData.append("file", this.fileList[0]);
      formData.append("year", this.year);
      formData.append("directorBy", this.directorBy);
      emergency(formData)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success("上传成功");
            this.addAnnualDrill = false;
            this.fileList = [];
            this.year = "";
            this.directorBy= ''
            this.loading = false;
            this.$refs.upload.clearFiles();
            this.pageNum = 1
            this.pageSize = 10
            this.getList();
          } else {
            this.$message.error(res.msg);
            this.loading = false;
            this.directorBy= ''
            this.$refs.upload.clearFiles();
            this.fileList = [];
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getChange(val) {
      this.planYear = val;
    },
    // 关闭弹框
    cancel() {
      this.year = "";
      this.directorBy = "";
      this.addAnnualDrill = false;
    },
    // 新增年度获取选择的年度
    changeYear(year) {
      this.year = new Date(year).getFullYear().toString();
    },
    // 文件上传前,进行一些类型判断和大小限制，将文件存到本地
    uploadHttpRequest(data) {
      if (
        // excel
        data.file.type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
        // excel
        data.file.type === "application/vnd.ms-excel"
      ) {
        this.fileList = [];
        this.fileList.push(data.file);
      } else {
        this.$message.warning("附件格式错误，请重新上传！");
        this.$refs.upload.clearFiles();
        this.fileList = [];
      }
    },
    // 下载模板
    derive() {
      // const hrefStr = encodeURI("/static/upload/年度演习计划模板.xlsx");
      // console.log(hrefStr);
      // window.location.href = hrefStr;
      this.download(
        "drill/emergency/importTemplate",
        {},
        `演习模板${new Date().getTime()}.xlsx`
      );
    },
    handleChange() {},
    handleSuccess() {
      this.$refs.upload.clearFiles(); // 上传成功之后清除历史记录
      this.accessory = "";
      this.fileList = [];
    },
    handleClose() {
      this.addAnnualDrill = false;
      this.fileList = [];
      this.year = "";
      this.$refs.upload.clearFiles();
    },
    add() {
      this.addAnnualDrill = true;
    },
    del(id) {
      this.$confirm("确认删除这条演习计划吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          removeYear(id).then((res) => {
            if (res.code === 200) {
              if (this.list.length === 1 && this.pageNum > 1) {
                this.pageNum -= 1;
              }
              this.getList();
              this.$message.success(res.msg);
            }
          });
        })
        .catch(() => {
          this.$message.error("已取消删除");
        });
    },
    getList() {
      getYearList({
        planName: this.planName,
        planYear: this.planYear,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }).then((res) => {
        if (res.code === 200) {
          this.list = res.rows;
          this.total = res.total;
        }
        console.log(res);
      });
    },
    reset() {
      this.planYear = "";
      this.planName = "";
      this.pageNum = 1;
      this.pageSize = 10;
      this.getList();
    },
    addCancel() {
      this.addAlert = false;
      this.addForm = {};
      this.$refs.addForm.resetFields();
    },
  },
};
</script>

<style lang="scss" scoped></style>
