<template>
  <div class="assessing-content ele-body">
    <el-card shadow="never" element-loading-background="rgba(255, 255, 255, 1)">
      <search
        :type="1"
        @search:task="updateParams($event)"
        @export="exportData($event)"
        :show-export="true"
      />
      <el-table
        highlight-current-row
        :data="dataList"
        :height="tableHeight"
        border
        :span-method="arraySpanMethod"
        v-loading="loading"
        ref="table"
      >
        <el-table-column
          type="index"
          width="50"
          align="center"
          label="编号"
        ></el-table-column>
        <el-table-column
          label="一级指标"
          min-width="80"
          align="center"
          prop="quota1"
        ></el-table-column>
        <el-table-column
          label="二级指标"
          min-width="80"
          align="center"
          prop="quota2"
        ></el-table-column>
        <el-table-column
          label="考核内容和计分细则"
          min-width="250"
          align="center"
          prop="content"
        >
        </el-table-column>
        <el-table-column
          label="小条内容"
          min-width="320"
          align="center"
          prop="itemContent"
        ></el-table-column>
        <el-table-column
          label="分值"
          width="50"
          align="center"
          prop="points"
        ></el-table-column>
        <el-table-column label="扣分" width="80" align="center">
          <template slot-scope="{ row, $index }">
            <div @click="showText($index, true)" style="height: 100%">
              <el-input
                :ref="'input' + $index"
                v-model="row.deptPoints"
                v-if="row.focus"
                @blur="
                  showText($index, false);
                  updatePoints(row, $index);
                "
              ></el-input>
              <span v-else>{{ row.deptPoints || 0 }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="区牵头单位"
          width="95"
          align="center"
          prop="leaderUnit"
        >
          <template slot-scope="{ row }">
            <pre>{{ row.leaderUnit }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="第一牵头部门" width="150" align="center">
          <template slot-scope="{ row }">
            <pre>{{ row.leaderDeptList | formatList }}</pre>
          </template>
        </el-table-column>
        <el-table-column
          label="第一牵头部门责任领导"
          width="170"
          align="center"
        >
          <template slot-scope="{ row }">
            <pre>{{ row.leaderPrincipalList | formatList }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="其他牵头部门" width="130" align="center">
          <template slot-scope="{ row }">
            <pre>{{ row.otherDeptList | formatList }}</pre>
          </template>
        </el-table-column>
        <el-table-column
          label="其他牵头部门责任领导"
          width="170"
          align="center"
        >
          <template slot-scope="{ row }">
            <pre>{{ row.otherPrincipalList | formatList }}</pre>
          </template>
        </el-table-column>
        <el-table-column
          label="配合部门"
          width="100"
          align="center"
          prop="cooperateDept"
        >
          <template slot-scope="{ row }">
            <pre>{{ row.cooperateDeptList | formatList }}</pre>
          </template>
        </el-table-column>
        <el-table-column
          label="配合部门责任领导"
          width="150"
          align="center"
          prop="cooperateDeptList"
        >
          <template slot-scope="{ row }">
            <pre>{{ row.cooperatePrincipalList | formatList }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="{ row }">
            <el-link
              slot="reference"
              type="primary"
              :underline="false"
              @click="edit(row)"
              :disabled="!row.id"
              icon="el-icon-edit"
              >编辑</el-link
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page.sync="page.page"
        :page-size="page.limit"
        :total="count"
        :background="true"
        layout="total, prev, pager, next, jumper"
        :pager-count="5"
        class="ele-pagination-circle"
        @current-change="getDataList()"
      />
      <el-dialog
        title="编辑考核内容"
        :visible.sync="showEdit"
        width="650px"
        custom-class="ele-dialog-form"
        :lock-scroll="true"
        :destroy-on-close="true"
        @closed="form = {}"
      >
        <!-- <el-scrollbar style="height: 50vh"> -->
        <el-row>
          <el-col :span="4" class="title">考核内容：</el-col>
          <el-col :span="18"
            ><el-input
              type="textarea"
              :rows="4"
              placeholder="请输入考核内容"
              v-model="form.itemContent"
            ></el-input
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="4" class="title"> 牵头部门： </el-col>
          <el-col :span="7">
            <treeselect
              :disable-branch-nodes="true"
              @input="changePrincipal($event, 'leader')"
              v-model="form.leaderDept"
              :options="formatDep"
              placeholder="请选择牵头部门"
              :defaultExpandLevel="2"
              :normalizer="
                (d) => {
                  return {
                    id: d.id,
                    label: d.name,
                    children:
                      d.children && d.children.length > 0
                        ? d.children
                        : undefined,
                  };
                }
              "
            />
          </el-col>
          <el-col :span="4" class="title"> 责任领导： </el-col>
          <el-col :span="7">
            <treeselect
              :disable-branch-nodes="true"
              v-model="form.leaderPrincipal"
              :options="principalList"
              placeholder="请选择牵头部门责任领导"
              :defaultExpandLevel="1"
              :normalizer="
                (d) => {
                  return {
                    id: d.id,
                    label: d.realname,
                    children:
                      d.children && d.children.length > 0
                        ? d.children
                        : undefined,
                  };
                }
              "
            />
          </el-col>
        </el-row>
        <div class="leader">
          <div
            style="display: flex; justify-content: center; margin-bottom: 20px"
          >
            <el-button type="primary" @click="addDept('other')"
              >添加其他牵头部门</el-button
            >
          </div>
          <!-- <span
              class="el-icon-circle-plus-outline add"
              @click="addDept('other')"
            ></span> -->
          <div
            style="position: relative"
            v-for="(item, index) of form.otherDept"
            :key="index"
          >
            <span
              class="el-icon-remove-outline delete"
              style="z-index: 10"
              @click="deleteDept(index, 'other')"
            ></span>
            <el-row>
              <el-col :span="4" class="title"> 其他牵头部门： </el-col>
              <el-col :span="7">
                <treeselect
                  :disable-branch-nodes="true"
                  @input="changePrincipal($event, 'other', index)"
                  v-model="form.otherDept[index]"
                  :options="formatDep"
                  placeholder="请选择其他牵头部门"
                  :defaultExpandLevel="2"
                  :normalizer="
                    (d) => {
                      return {
                        id: d.id,
                        label: d.name,
                        children:
                          d.children && d.children.length > 0
                            ? d.children
                            : undefined,
                      };
                    }
                  "
                />
              </el-col>
              <el-col :span="4" class="title"> 责任领导： </el-col>
              <el-col :span="7">
                <treeselect
                  :disable-branch-nodes="true"
                  v-model="form.otherPrincipal[index]"
                  :options="principalList"
                  placeholder="请选择其他牵头部门责任领导"
                  :defaultExpandLevel="1"
                  :normalizer="
                    (d) => {
                      return {
                        id: d.id,
                        label: d.realname,
                        children:
                          d.children && d.children.length > 0
                            ? d.children
                            : undefined,
                      };
                    }
                  "
                />
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="cooperate">
          <div
            style="display: flex; justify-content: center; margin-bottom: 20px"
          >
            <el-button type="primary" @click="addDept('cooperate')"
              >添加配合部门</el-button
            >
          </div>
          <!-- <span
              class="el-icon-circle-plus-outline add"
              @click="addDept('cooperate')"
            ></span> -->
          <div
            style="position: relative"
            v-for="(item, index) of form.cooperateDept"
            :key="index"
          >
            <span
              class="el-icon-remove-outline delete"
              style="z-index: 10"
              @click="deleteDept(index, 'cooperate')"
            ></span>
            <el-row>
              <el-col :span="4" class="title">配合部门： </el-col>
              <el-col :span="7">
                <treeselect
                  :disable-branch-nodes="true"
                  @input="changePrincipal($event, 'cooperate')"
                  v-model="form.cooperateDept[index]"
                  :options="formatDep"
                  placeholder="请选择配合部门"
                  :defaultExpandLevel="2"
                  :normalizer="
                    (d) => {
                      return {
                        id: d.id,
                        label: d.name,
                        children:
                          d.children && d.children.length > 0
                            ? d.children
                            : undefined,
                      };
                    }
                  "
                />
              </el-col>
              <el-col :span="4" class="title"> 责任领导： </el-col>
              <el-col :span="7">
                <treeselect
                  :disable-branch-nodes="true"
                  v-model="form.cooperatePrincipal[index]"
                  :options="principalList"
                  placeholder="请选择配合部门责任领导"
                  :defaultExpandLevel="1"
                  :normalizer="
                    (d) => {
                      return {
                        id: d.id,
                        label: d.realname,
                        children:
                          d.children && d.children.length > 0
                            ? d.children
                            : undefined,
                      };
                    }
                  "
                />
              </el-col>
            </el-row>
          </div>
        </div>
        <el-row>
          <el-col :span="4" class="title">分值：</el-col>
          <el-col :span="7"
            ><el-input placeholder="请输入分值" v-model="form.points"></el-input
          ></el-col>
        </el-row>
        <!-- </el-scrollbar> -->
        <div slot="footer">
          <el-button type="primary" @click="save">确定</el-button>
          <el-button @click="showEdit = false">取消</el-button>&nbsp;
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import search from "../search";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";
import { mapGetters } from "vuex";
import api from "@/api/second/taskSummary";
import { mergeSpan } from "@/utils/mixin";
import editApi from "@/api/second/segmentation/basicTable";
export default {
  components: {
    search,
    Treeselect,
  },
  mixins: [
    mergeSpan([
      { name: "quota1", col: [1] },
      { name: "quota2", col: [2] },
      { name: "content", col: [3] },
    ]),
  ],
  data() {
    return {
      searchParams: {},
      dataList: [],
      loading: false,
      showEdit: false,
      form: {},
      count: 0,
      tableHeight: document.documentElement.clientHeight - 260,
      page: {
        page: 1,
        limit: Math.floor(
          (document.documentElement.clientHeight - 260 - 45) / 45
        ),
      },
      preValue: null,
    };
  },
  created() {
    this.getDataList();
    this.$store.dispatch("base/getPrincipalList");
  },
  computed: {
    ...mapGetters(["formatDep", "principalList", "department"]),
  },
  filters: {
    formatList(val) {
      if (val) {
        return val.join("\n");
      }
    },
  },
  methods: {
    updatePoints(row, index) {
      if (row.deptPoints == this.preValue) {
        return;
      }
      if (
        row.deptPoints < 0 ||
        row.deptPoints > row.points ||
        !row.deptPoints.trim()
      ) {
        this.$message({
          type: "warning",
          message: "请输入数值0~" + row.points,
        });
        let data = this.dataList;
        data[index].deptPoints = this.preValue;
        this.dataList = data;
        return;
      }
      editApi
        .editItem({
          itemId: row.id,
          expectedPoints: row.deptPoints,
        })
        .then((res) => {
          this.$message({ type: "success", message: "修改成功" });
        })
        .catch(() => {
          this.$message.error("修改失败");
          this.getDataList();
        });
    },
    showText(index, bool) {
      try {
        let data = this.dataList;
        // data[index].focus = bool;
        // this.dataList = data;
        this.$set(this.dataList[index], "focus", bool);
        if (bool) {
          this.preValue = data[index].deptPoints;
        }
        this.$nextTick(() => {
          this.$refs["input" + index].focus();
        });
      } catch (e) {
        console.log(e);
      }
    },
    exportData(data) {
      this.loading = true;
      api
        .exportBasicList(
          Object.assign({ sheetName: "基础目标任务细分小条" }, data)
        )
        .then((res) => {
          if (res.data.code == 0) {
            // window.open(res.data.data);
            // window.location.href=res.data.data;
            window.location.href = res.data.data;
            this.$message({
              type: "success",
              message: "导出成功",
            });
          } else {
            this.$message({
              type: "warning",
              message: "暂无数据",
            });
          }
        })
        .catch((e) => {
          console.log(e);
          this.$message.error("暂无数据");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    changePrincipal(e, type, index) {
      if (type == "other") {
        let depts = this.form.otherDept;

        let nameIds = [];
        depts.forEach((dept) => {
          this.department.forEach((item) => {
            if (item.id == dept) {
              nameIds.push(parseInt(item.principal));
            }
          });
        });
        this.$set(this.form, "otherPrincipal", nameIds);
      }
      if (type == "cooperate") {
        let depts = this.form.cooperateDept;
        let nameIds = [];
        depts.forEach((dept) => {
          this.department.forEach((item) => {
            if (item.id == dept) {
              nameIds.push(parseInt(item.principal));
            }
          });
        });
        this.$set(this.form, "cooperatePrincipal", nameIds);
      }
      if (type == "leader") {
        let nameId;
        let id = this.form.leaderDept;
        this.department.forEach((item) => {
          if (item.id == id) {
            nameId = item.principal;
            return;
          }
        });
        this.$set(this.form, "leaderPrincipal", nameId && parseInt(nameId));
      }
    },
    addDept(type) {
      if (type == "other") {
        this.form.otherDept = this.form.otherDept || [];
        this.form.otherPrincipal = this.form.otherPrincipal || [];
        this.form.otherDept.push(undefined);
        this.form.otherPrincipal.push(undefined);
      }
      if (type == "cooperate") {
        this.form.cooperateDept = this.form.cooperateDept || [];
        this.form.cooperatePrincipal = this.form.cooperatePrincipal || [];
        this.form.cooperateDept.push(undefined);
        this.form.cooperatePrincipal.push(undefined);
      }
    },
    deleteDept(index, type) {
      if (type == "other") {
        this.form.otherDept.splice(index, 1);
        this.form.otherPrincipal.splice(index, 1);
      }
      if (type == "cooperate") {
        this.form.cooperateDept.splice(index, 1);
        this.form.cooperatePrincipal.splice(index, 1);
      }
    },
    updateParams(data) {
      this.searchParams = data;
      this.resetCurrentPage();
      this.getDataList();
    },
    resetCurrentPage() {
      let page = this.page;
      page.page = 1;
      this.page = page;
    },
    getDataList() {
      try {
        this.$refs.table.bodyWrapper.scrollTop = 0;
      } catch (e) {}
      this.loading = true;
      api
        .getBasicTableList(Object.assign({}, this.page, this.searchParams))
        .then((res) => {
          let data = res.data.data;
          this.count = data.total;
          this.dataList = this.reduceData(data.records);
        })
        .catch((e) => {
          this.dataList = [];
          this.count = 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    edit(row) {
      this.showEdit = true;
      let form = JSON.parse(JSON.stringify(row));
      form.cooperateDept =
        form.cooperateDept &&
        form.cooperateDept.split(",").map((item) => parseInt(item));
      form.cooperatePrincipal =
        form.cooperatePrincipal &&
        form.cooperatePrincipal.split(",").map((item) => parseInt(item));
      form.otherDept =
        form.otherDept &&
        form.otherDept.split(",").map((item) => parseInt(item));
      form.otherPrincipal =
        form.otherPrincipal &&
        form.otherPrincipal.split(",").map((item) => parseInt(item));
      this.form = form;
    },
    save() {
      this.loading = true;
      let form = JSON.parse(JSON.stringify(this.form));
      let params = [
        "content",
        "points",
        "leaderDept",
        "leaderPrincipal",
        // "otherDept",
        // "otherPrincipal",
        // "cooperateDept",
        // "cooperatePrincipal",
      ];
      for (let param of params) {
        if (Array.isArray(form[param])) {
          for (let item of form[param]) {
            if (!item && item != 0) {
              this.$message({
                type: "warning",
                message: "请完善信息",
              });
              return;
            }
          }
        } else {
          if (!form[param]) {
            this.$message({
              type: "warning",
              message: "请完善信息",
            });
            return;
          }
          if (
            form[param] &&
            typeof form[param] == "string" &&
            form[param].trim() == ""
          ) {
            this.$message({
              type: "warning",
              message: "请完善信息",
            });
            return;
          }
          if (
            param == "points" &&
            parseInt(form[param]) !== parseInt(form[param])
          ) {
            this.$message({
              type: "warning",
              message: "分值请输入数字",
            });
            return;
          }
        }
      }
      form.cooperateDept = form.cooperateDept && form.cooperateDept.join(",");
      // form.leaderDept = form.leaderDept && form.leaderDept.join(",");
      // form.leaderPrincipal =
      //   form.leaderPrincipal && form.leaderPrincipal.join(",");
      form.cooperatePrincipal =
        form.cooperatePrincipal && form.cooperatePrincipal.join(",");
      form.otherDept = form.otherDept && form.otherDept.join(",");
      form.otherPrincipal =
        form.otherPrincipal && form.otherPrincipal.join(",");
      editApi
        .editItem(Object.assign({}, form))
        .then((res) => {
          if (res.data.code == 0) {
            this.showEdit = false;
            this.$message({
              type: "success",
              message: "提交申请成功",
            });
            this.getDataList();
          } else {
            this.$message({
              type: "error",
              message: res.data.msg,
            });
          }
        })
        .catch((e) => {
          this.showEdit = false;
          this.$message({
            type: "error",
            message: "提交申请失败",
          });
        })
        .finally(() => {
          this.form = {};
          this.loading = false;
        });
    },
  },
};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
  display: flex;
  align-content: center;
  padding: 0 20px 0 10px;
}
.el-col {
  text-align: right;
}
.title {
  margin-right: 10px;
  line-height: 36px;
}
.leader,
.cooperate {
  position: relative;
}
.add {
  font-size: 20px;
  position: absolute;
  left: 15px;
  transform: translateX(-50%);
  top: 8px;
  color: #4d9efc;
  z-index: 10;
}
.delete {
  font-size: 20px;
  position: absolute;
  right: 20px;
  top: 8px;
  color: #fa4953;
}
/deep/ .el-dialog__body {
  padding-right: 0;
  padding-left: 0;
  max-height: 60vh;
  overflow-y: scroll;
}
</style>