<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" size="small" v-show="showSearch" label-width="68px">
      <el-form-item label="所属年份" prop="planYear">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.planYear"
                        type="year"
                        placeholder="选择年份">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="当前状态" prop="itemStatus">
        <el-select v-model="queryParams.itemStatus" placeholder="请选择当前状态">
          <el-option
            v-for="dict in itemStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="personInCharge">
        <el-select v-model="queryParams.personInCharge" placeholder="请选择负责人">
          <el-option
            v-for="dict in userList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="归属部门" prop="deptId" style="width: 268px;">
        <treeselect style="width: 200px;" v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
      </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 class="colorMark">
      <svg-icon icon-class="rectanglered" class="rectanglered"></svg-icon>1-15天内到期
      <svg-icon icon-class="rectangleYellow" class="rectangleYellow"></svg-icon>16-30天内到期
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddPlan"
          v-hasPermi="['branch:plan:add']"
        >新增标题</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :cell-style="tableCellStyle" v-loading="loading" :data="planList" @selection-change="handleSelectionChange" :height="clientHeight" border :span-method="objectSpanMethod">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" align="center" prop="planTitle" width="200" />
      <el-table-column label="内容" align="center" prop="itemContent"/>
      <el-table-column label="计划实施时间" align="center" prop="planTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" align="center" prop="itemStatus" :formatter="itemStatusFormat" />
      <el-table-column label="实际完成日期" align="center" prop="actualTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.actualTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="personInChargeString" />
      <el-table-column label="操作" 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="['branch:planitem:edit']"
            v-if="scope.row.itemId != null"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['branch:planitem:remove']"
            v-if="scope.row.itemId != null"
          >删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="240" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['branch:planitem:add']"
          >新增条目</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdatePlan(scope.row)"
            v-hasPermi="['branch:plan:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeletePlan(scope.row)"
            v-hasPermi="['branch:plan: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"
    />

    <!-- 添加或修改支部年度工作计划条目对话框 -->
    <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="planTitle">
          <el-input v-model="form.planTitle" disabled />
        </el-form-item>
        <el-form-item label="内容" prop="itemContent">
          <el-input v-model="form.itemContent" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="计划实施时间" prop="planTime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.planTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择计划实施时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="当前状态" prop="itemStatus">
          <el-select v-model="form.itemStatus" placeholder="请选择当前状态">
            <el-option
              v-for="dict in itemStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实际完成日期" prop="actualTime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.actualTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择实际完成日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="负责人" prop="host">
          <el-select v-model="form.personInCharge" multiple placeholder="请选择负责人">
            <el-option
              v-for="dict in userList"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属部门" prop="deptId">
            <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" 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="titlePlan" :visible.sync="openPlan" width="500px" append-to-body>
      <el-form ref="formPlan" :model="formPlan" :rules="rulesPlan" label-width="80px">
        <el-form-item label="标题" prop="planTitle">
          <el-input v-model="formPlan.planTitle" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="所属年份" prop="planYear">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="formPlan.planYear"
                          type="year"
                          placeholder="选择年份">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="归属部门" prop="deptId">
          <treeselect v-model="formPlan.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormPlan">确 定</el-button>
        <el-button @click="cancelPlan">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :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">
                将文件拖到此处，或
                <em>点击上传</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">下载模板</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 { listPlanitem, getPlanitem, delPlanitem, addPlanitem, updatePlanitem, exportPlanitem, importTemplate} from "@/api/branch/planitem";
import { listPlan, getPlan, delPlan, addPlan, updatePlan, exportPlan, importTemplatePlan} from "@/api/branch/plan";
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 { listUserNoPage } from "@/api/system/user";

export default {
  name: "Planitem",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      planList: [],
      // 弹出层标题
      title: "",
      titlePlan: "",
      titleListPlan: "",
      // 部门树选项
      deptOptions: [],
      clientHeight:300,
      // 是否显示弹出层
      open: false,
      openPlan: false,
      openListPlan: false,
      // 当前状态字典
      itemStatusOptions: [],
      // 用户列表
      userList: [],
      // 用户导入参数
      upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/branch/planitem/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        itemId: null,
        planId: null,
        itemContent: null,
        planTime: null,
        itemStatus: null,
        actualTime: null,
        personInCharge: null,
        deptId: null,
      },
      // 表单参数
      form: {},
      formPlan: {},
      // 表单校验
      rules: {
        planId: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        itemContent: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "归属部门不能为空", trigger: "blur" }
        ],
      },
      rulesPlan: {
        planTitle: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        planYear: [
          { required: true, message: "所属年份不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "归属部门不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
        // 根据名称筛选部门树
        deptName(val) {
            this.$refs.tree.filter(val);
        }
   },
  created() {
      //设置表格高度对应屏幕高度
      this.$nextTick(() => {
          this.clientHeight = document.body.clientHeight -250
      })
    // 设置搜索条件年份为当年
    this.setYear();
    this.getList();
    this.getTreeselect();
    this.getDicts("plan_item_status").then(response => {
      this.itemStatusOptions = response.data;
    });
  },
  methods: {
    // 单元格样式
    tableCellStyle( {row, column, rowIndex, columnIndex} ) {
      console.log(row.planTime)
      if (columnIndex === 0 ||columnIndex === 7) {
        return;
      }
      let today = new Date(); // 当前时间
      let planTime = new Date(row.planTime);
      if (today.getTime() < planTime.getTime()) {
        let difference = planTime.getTime() - today.getTime(); // 时间差
        if (row.planTime != null && row.planTime != '' && row.itemStatus != '1') {
          if (difference < 16 * 24 * 60 * 60 * 1000) {  // 到期时间 - 当前时间 < 16
            return "background-color: rgba(203, 0, 0, 1); color: rgb(255, 255, 255);";
          } else if (difference >= 16 * 24 * 60 * 60 * 1000
            && difference <= 30 * 24 * 60 * 60 * 1000) {  // 16 <= 到期时间 - 当前时间 <= 30
            return "background-color: rgba(255, 255, 0, 1);";
          }
        }
      }
    },
    /** 设置搜索条件年份 */
    setYear() {
      this.queryParams.planYear = new Date();
    },
    /** 查询用户列表 */
    getUserList() {
      listUserNoPage().then(response => {
        let rows = response.data;
        let userList = [];
        for(let i = 0; i < rows.length; i++) {
          if (rows[i].userName != "admin") {
            let user = { "dictValue" : rows[i].userId, "dictLabel" : rows[i].nickName};
            userList.push(user);
          }
        }
        this.userList = userList;
      });
    },
    /** 计算单元格合并行数 */
    getSpanArr(list) {
      list.forEach(item => {
        item.rowspan = 1;
      });
      for (let i = 0; i < list.length; i++) {
        for (let j = i + 1; j < list.length; j++) {
          //此处可根据相同字段进行合并
          if (list[i].planId == list[j].planId) {
            list[i].rowspan++;
            list[j].rowspan--;
          }
        }
        // 这里跳过已经重复的数据
        i = i + list[i].rowspan - 1;
      }
      this.planList = list;
    },
    /** 单元格合并 */
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1 || columnIndex == 8) {
        return {
          rowspan: row.rowspan,
          colspan: 1,
        };
      }
    },
    /** 查询支部年度工作计划条目列表 */
    getList() {
      this.loading = true;
      listUserNoPage().then(response => {
        let rows = response.data;
        let userList = [];
        for(let i = 0; i < rows.length; i++) {
          if (rows[i].userName != "admin") {
            let user = { "dictValue" : rows[i].userId, "dictLabel" : rows[i].nickName};
            userList.push(user);
          }
        }
        this.userList = userList;
      }).then(() => {
        return listPlan({
          "planYear": this.queryParams.planYear.getFullYear(),
          "itemStatus": this.queryParams.itemStatus,
          "personInCharge": this.queryParams.personInCharge,
          "deptId": this.queryParams.deptId
        });
      }).then(response => {
        let rows = response.rows;
        let planList = [];
        for (let i = 0; i < rows.length; i ++) {
          let itemList = rows[i].itemList;
            if (itemList.length == 0) {
              let row = {...rows[i]};
              planList.push(row);
            } else {
              for (let j = 0; j < itemList.length; j++) {
                if (itemList[j].personInCharge != null) {
                  let personInCharge = itemList[j].personInCharge.split(",");
                  let personInChargeString = "";
                  for (let k = 0; k < personInCharge.length; k++) {
                    if (k > 0) {
                      personInChargeString += "、" + this.selectDictLabel(this.userList, personInCharge[k]);
                    } else {
                      personInChargeString += this.selectDictLabel(this.userList, personInCharge[k]);
                    }
                  }
                  itemList[j].personInChargeString = personInChargeString;
                }
                let row = {...rows[i], ...itemList[j]};
                planList.push(row);
              }
            }
        }
        this.planList = planList;
        this.getSpanArr(this.planList);
        this.total = response.total;
        this.loading = false;
      });
    },
     /** 查询部门下拉树结构 */
     getTreeselect() {
          treeselect().then(response => {
              this.deptOptions = response.data;
          });
     },
    // 当前状态字典翻译
    itemStatusFormat(row, column) {
      return this.selectDictLabel(this.itemStatusOptions, row.itemStatus);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelPlan() {
      this.openPlan = false;
      this.resetPlan();
    },
    // 表单重置
    reset() {
      this.form = {
        itemId: null,
        planId: null,
        itemContent: null,
        planTime: null,
        itemStatus: null,
        actualTime: null,
        personInCharge: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        deptId: null,
      };
      this.resetForm("form");
    },
    resetPlan() {
      this.formPlan = {
        planId: null,
        planTitle: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        deptId: null,
      };
      this.resetForm("formPlan");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.itemId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.form.planId = row.planId;
      this.form.planTitle = row.planTitle;
      this.form.deptId = row.deptId;
      this.open = true;
      this.title = "添加支部年度工作计划条目";
    },
    handleAddPlan() {
      this.resetPlan();
      this.openPlan = true;
      this.titlePlan = "添加支部年度工作计划标题";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      this.reset();
      const itemId = row.itemId || this.ids
      getPlanitem(itemId).then(response => {
        this.form = response.data;
        this.form.planTitle = row.planTitle;
        if (this.form.personInCharge != null) {
          this.form.personInCharge = this.form.personInCharge.split(",").map(Number);
        }
        this.open = true;
        this.title = "修改支部年度工作计划条目";
      });
    },
    handleUpdatePlan(row) {
      // row.isEdit = true;
      this.resetPlan();
      const planId = row.planId || this.ids
      getPlan(planId).then(response => {
        this.formPlan = response.data;
        this.openPlan = true;
        this.titlePlan = "修改支部年度工作计划标题";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.personInCharge != null) {
        this.form.personInCharge = this.form.personInCharge.join();
      }
        this.$refs["form"].validate(valid => {
            if (valid) {
                if (this.form.itemId != null) {
                    updatePlanitem(this.form).then(response => {
                        this.$modal.msgSuccess("修改成功");
                        this.open = false;
                        this.getList();
                    });
                } else {
                    addPlanitem(this.form).then(response => {
                        this.$modal.msgSuccess("新增成功");
                        this.open = false;
                        this.getList();
                    });
                }
            }
        });
    },
    submitFormPlan() {
      this.$refs["formPlan"].validate(valid => {
        if (valid) {
          if (typeof(this.formPlan.planYear) != 'string') {
            this.formPlan.planYear = this.formPlan.planYear.getFullYear();
          }
          if (this.formPlan.planId != null) {
            updatePlan(this.formPlan).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openPlan = false;
              this.getList();
            });
          } else {
            addPlan(this.formPlan).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openPlan = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const itemIds = row.itemId || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPlanitem(itemIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
    },
    handleDeletePlan(row) {
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delPlan(row.planId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有支部年度工作计划数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportPlanitem(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
      /** 导入按钮操作 */
      handleImport() {
          this.upload.title = "用户导入";
          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, "导入结果", { dangerouslyUseHTMLString: true });
          this.getList();
      },
      // 提交上传文件
      submitFileForm() {
          this.$refs.upload.submit();
      }
  }
};
</script>

<style>
    /** 文本换行符处理 */
    .el-table .cell{
        white-space: pre-wrap;
    }
    /** textarea字体 */
    textarea {
        font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
    }
    .colorMark {
      color: #6f6f6f;
      text-align: right;
      font-weight:bold;
      font-size: 13px;
      padding-bottom: 5px;
    }
    .rectanglered {
      width: 40px !important;
      height: 20px !important;
    }
    .rectangleYellow {
      width: 40px !important;
      height: 20px !important;
    }
</style>
