<template>
  <div style="background:#eee;padding: 20px">
    <Card :bordered="false">
      <p slot="title" style="height: 35px;">
        <Select v-model="taskRuleId" style="width:200px">
          <Option
            v-for="item in taskRuleList"
            :value="item.value"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
        <el-button
          type="primary"
          style="float: right;margin-right: 30px;"
          @click="renderTaskPage"
          >任务列表</el-button
        >
      </p>
      <p style="height: 30px;">
        <span style="margin: 5px;"
          >{{ socreShtgTxt }}{{ socreShtg }}/应完成{{ socreYjwc }}</span
        >
      </p>
      <p>
        <Progress
          :percent="socreShtgRate"
          :stroke-width="30"
          status="active"
          text-inside
        />
      </p>
    </Card>

    <Card style="margin-top: 10px;">
      <div>
        <Table border :columns="totalZjScoreColumns" :data="totalZjScoreData">
          <template slot-scope="{ row }" slot="name">
            <strong>{{ row.name }}</strong>
          </template>
        </Table>
      </div>
      <!--      <div style="margin-top: 30px;">-->
      <!--        <el-button type="primary" @click="showZjDiag">分配</el-button>-->
      <!--      </div>-->
    </Card>

    <Card style="margin-top: 10px;">
      <p slot="title">
        分配积分
      </p>
      <p>
        <avue-crud
          ref="crud"
          :data="tableData"
          v-model="form"
          :before-open="beforeOpen"
          :permission="permissionList"
          :table-loading="tableLoading"
          :option="tableOption"
          @on-load="getList"
          @search-change="searchChange"
          @refresh-change="refreshChange"
          @size-change="sizeChange"
          @current-change="currentChange"
          @row-update="handleUpdate"
          @row-save="handleSave"
          @row-del="rowDel"
        >
          <template slot-scope="scope" slot="kfpjfForm">
            <el-tag style="font-size: 14px;font-weight: bold">{{
              syScore
            }}</el-tag>
          </template>
          <template slot="menu" slot-scope="scope">
            <el-button
              :hidden="scope.row.isConduct == '1'"
              type="text"
              size="small"
              icon="el-icon-edit"
              @click="handleEdit(scope.row, scope.index)"
              >编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              icon="el-icon-edit"
              :hidden="scope.row.packageAduitStatus == '1'"
              @click="zzAdudit(scope.row, scope.index)"
              >终止
            </el-button>
          </template>
        </avue-crud>
      </p>
    </Card>
    <!--    <Modal-->
    <!--      title="新增 分配积分"-->
    <!--      v-model="modalZj"-->
    <!--      :mask-closable="false">-->
    <!--      <p style="margin-top: 20px;">-->
    <!--        积分包ID     <Input v-model="this.jifenbao.id" placeholder="请输入 积分包ID" style="width: 300px" />-->
    <!--      </p>-->
    <!--      <p style="margin-top: 20px;">-->
    <!--        积分包值     <Input v-model="this.jifenbao.id" placeholder="请输入  积分包值" style="width: 300px" />-->
    <!--      </p>-->
    <!--      <p style="margin-top: 20px;margin-bottom: 20px;">-->
    <!--        分配对象     <Select v-model="model11" filterable STYLE="width: 62%;" placeholder="可输入字符筛选">-->
    <!--        <Option v-for="item in agentList" :value="item.value" :key="item.value">{{ item.label }}</Option>-->
    <!--      </Select>-->
    <!--      </p>-->
    <!--    </Modal>-->
  </div>
</template>
<script>
import {
  fetchList,
  getListRule,
  getTotalData,
  getObj,
  addObj,
  putObj,
  delObj,
  selWmscorepackageList
} from "@/api/wmscorepackage";
import { selWmtaskruleList } from "@/api/wmtaskrule";
import { drugEntList } from "@/api/wmdadrugent";
import { tableOptionFp2 } from "@/const/crud/wmscorepackage";
import { getObjDept } from "@/api/admin/dept";

import { mapGetters } from "vuex";
export default {
  data() {
    return {
      entLevel: 0,
      isShowLevel2Id: false,
      isFirstInit: true,
      taskRuleId: 0,
      socreYjwc: 0,
      socreShtg: 0,
      socreShtgRate: 0,
      socreShtgTxt: "已提交",
      socreZj: 0,
      oldEditRow: null,
      jifenbao: {
        id: "",
        value: "",
        deptId: ""
      },
      modalAgent: "",
      modalZj: false,
      syScore: 0,
      taskRuleList: [
        // {
        //   value: 'New York',
        //   label: 'New York'
        // }
      ],
      agentList: [
        // {
        //   value: 'New York',
        //   label: 'New York'
        // }
      ],
      totalScoreModel: "",
      totalZjScoreColumns: [
        {
          title: "应完成",
          key: "ywc",
          align: "center"
        },
        {
          title: "已分配",
          key: "yfp",
          align: "center"
        },
        {
          title: "已收到",
          key: "ysd",
          align: "center"
        },
        {
          title: "已提交",
          key: "ytj",
          align: "center"
        },
        {
          title: "审核通过",
          key: "shtg",
          align: "center"
        },
        {
          title: "任务库剩余",
          key: "rwksy",
          align: "center"
        }
      ],
      totalZjScoreData: [
        {
          ywc: 0,
          yfp: 0,
          ysd: 0,
          ytj: 0,
          shtg: 0,
          rwksy: 0
        }
      ],
      totalFpScoreColumns: [
        {
          title: "积分包ID",
          key: "jfbid",
          align: "center"
        },
        {
          title: "分配对象",
          key: "fpdx",
          align: "center"
        },
        {
          title: "应完成",
          key: "ywc",
          align: "center"
        },
        {
          title: "已提交",
          key: "ytj",
          align: "center"
        },
        {
          title: "审核通过",
          key: "shtg",
          align: "center"
        },
        {
          title: "进度",
          key: "jd",
          align: "center"
        },
        {
          title: "操作",
          key: "action",
          width: 150,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "el-button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.show(params.index);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.remove(params.index);
                    }
                  }
                },
                "审核"
              )
            ]);
          }
        }
      ],
      searchForm: {},
      tableData: [],
      form: {},
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 1000 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOptionFp2
    };
  },
  computed: {
    ...mapGetters(["permissions", "userInfo"]),

    permissionList() {
      return {
        // addBtn: this.vaildData(this.permissions.admin_wmscorepackage_add, false),
        // delBtn: this.vaildData(this.permissions.admin_wmscorepackage_del, false),
        // editBtn: this.vaildData(this.permissions.admin_wmscorepackage_edit, false)
      };
    }
  },
  mounted() {
    this.init();
  },
  watch: {
    taskRuleId: function(val, oldVal) {
      if ("" != val && "0" != val && 0 != val) {
        this.init();
      }
    },
    "form.typeid": function(val, oldVal) {
      if ("" != val) {
        var obj = tableOptionFp2;
        obj.column[4].addDisplay = false;
        obj.column[5].addDisplay = false;
        obj.column[6].addDisplay = false;
        obj.column[9].addDisplay = false;

        if (val == 2) {
          if (1 == this.entLevel) {
            obj.column[5].addDisplay = true;
            obj.column[5].addDisplay = true;
          } else {
            obj.column[5].addDisplay = false;
          }
        } else if (val == 3) {
          //obj.column[15].addDisplay=true;
          obj.column[6].addDisplay = true;
        } else if (val == 4) {
          // obj.column[13].addDisplay=true;
          obj.column[9].addDisplay = true;
        }
      }
    },
    entLevel: function(val, oldVal) {
      if ("0" != val) {
        var obj = tableOptionFp2;
        if (val == 1) {
          // obj.column[3].hide=false;
          // obj.column[4].hide=false;
          // obj.column[5].hide=true;
        } else {
          // obj.column[3].hide=false;
          obj.column[4].hide = true;
          obj.column[5].hide = true;
        }
      }
    }
  },
  methods: {
    handleEdit(row, index) {
      var obj = tableOptionFp2;
      this.oldEditRow = row;
      obj.column[6].editDisplay = false;
      obj.column[9].editDisplay = false;
      if (row.typeid == 3) {
        obj.column[6].editDisplay = true;
        obj.column[6].editDisabled = true;
      }

      if (row.typeid == 4) {
        obj.column[9].editDisplay = true;
      }

      this.$refs.crud.rowEdit(row, index);
    },
    init() {
      if (this.isFirstInit) {
        var obj = {
          //   typeid:5,
          //   taskRuleId:1
        };
        selWmtaskruleList(obj)
          .then(data => {
            var date = new Date();
            var nowYear = date.getFullYear();
            var nowMonth =
              date.getMonth() + 1 < 10
                ? "0" + (date.getMonth() + 1)
                : date.getMonth() + 1;
            var date_str = nowYear + "-" + nowMonth;
            var answer = data.data.data;
            if (undefined != data.data) {
              var answer = data.data.data;
              for (var i = 0; i < answer.length; i++) {
                if (answer[i].ruleMonth == date_str) {
                  this.taskRuleId = answer[i].id;
                }
                this.taskRuleList.push({
                  value: answer[i].id,
                  label: answer[i].ruleMonth
                });
              }
            }
          })
          .catch(() => {
            loading();
          });

        drugEntList(obj)
          .then(data => {
            if (undefined != data.data) {
              var answer = data.data.data;
              for (var i = 0; i < answer.length; i++) {
                this.agentList.push({
                  value: answer[i].id,
                  label: answer[i].entname
                });
              }
            }
          })
          .catch(() => {
            loading();
          });
        this.getObjDept1();
        this.isFirstInit = false;
      } else {
        this.refreshChange();
      }
    },
    showZjDiag() {
      this.modalZj = true;
    },
    remove(index) {
      this.data6.splice(index, 1);
    },
    getList(page, params) {
      this.searchForm.taskRuleId = this.taskRuleId;
      this.tableLoading = true;
      getListRule(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          let resData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
          this.tableData = resData;
          var yfp = 0;
          var ysd = 0;
          var ytj = 0;
          var shtg = 0;
          var rwksy = 0;
          var answer = resData;
          for (var i = 0; i < answer.length; i++) {
            if (undefined != answer[i].score) {
              yfp += answer[i].score;
            }
            if (undefined != answer[i].ytj) {
              ysd += answer[i].ytj;
            }

            if (undefined != answer[i].dsh) {
              ytj += answer[i].dsh;
            }

            if (undefined != answer[i].ysh) {
              shtg += answer[i].ysh;
            }
          }
          this.totalZjScoreData[0].yfp = yfp;
          this.totalZjScoreData[0].ysd = ysd;
          this.totalZjScoreData[0].ytj = ytj;
          this.totalZjScoreData[0].shtg = shtg;
          this.totalZjScoreData[0].rwksy = rwksy;
          if (this.entLevel == 1) {
            this.socreShtg = ytj;
          } else {
            this.socreShtg = ysd;
          }
          if (this.entLevel == 1) {
            if (ytj > 0 && this.totalZjScoreData[0].ywc > 0) {
              var socre = parseFloat(
                (ytj * 100) / this.totalZjScoreData[0].ywc
              ).toFixed(0);
              if (socre > 100) {
                socre = 100;
              }
              this.socreShtgRate = parseInt(socre);
            }
          } else {
            if (ysd > 0 && this.totalZjScoreData[0].ywc > 0) {
              var socre = parseFloat(
                (ysd * 100) / this.totalZjScoreData[0].ywc
              ).toFixed(0);
              if (socre > 100) {
                socre = 100;
              }
              this.socreShtgRate = parseInt(socre);
            }
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    getTotalTableData() {
      if (undefined == this.taskRuleId || this.taskRuleId == 0) {
        return false;
      }
      var obj = {
        taskRuleId: this.taskRuleId
      };
      getTotalData(obj)
        .then(response => {
          let answer = response.data.data;
          var ywc = 0;
          var yfp = 0;
          var ysd = 0;
          var ytj = 0;
          var shtg = 0;
          var rwksy = 0;
          if (answer.length > 0) {
            for (var i = 0; i < answer.length; i++) {
              if (this.userInfo.deptId == answer[i].sendPackageDeptId) {
                yfp += answer[i].score;
              } else {
                if (undefined != answer[i].score) {
                  ywc += answer[i].score;
                }

                if (undefined != answer[i].ytj) {
                  ysd += answer[i].ytj;
                }

                if (undefined != answer[i].ysh) {
                  shtg = answer[i].ysh;
                }
              }
            }
          }
          this.socreYjwc = ywc;
          // this.socreShtg=shtg;
          if (this.entLevel == 1) {
            if (this.totalZjScoreData[0].ytj > 0 && ywc > 0) {
              var socre = parseFloat(
                (this.totalZjScoreData[0].ytj * 100) / ywc
              ).toFixed(0);
              if (socre > 100) {
                socre = 100;
              }
              this.socreShtgRate = parseInt(socre);
            }
          } else {
            if (this.totalZjScoreData[0].ysd > 0 && ywc > 0) {
              var socre = parseFloat(
                (this.totalZjScoreData[0].ysd * 100) / ywc
              ).toFixed(0);
              if (socre > 100) {
                socre = 100;
              }
              this.socreShtgRate = parseInt(socre);
            }
          }

          // this.totalZjScoreData[0].ywc=ywc;
          this.totalZjScoreData[0].ywc = ywc;
          // this.totalZjScoreData.push({
          //   ywc:ywc,
          //   yfp:yfp,
          //   ysd:ysd,
          //   ytj:ytj,
          //   shtg:shtg,
          //   rwksy:rwksy
          // });
        })
        .catch(() => {});
    },
    rowDel: function(row, index) {
      this.$confirm("是否确认删除ID为" + row.id, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delObj(row.id);
        })
        .then(data => {
          this.$message.success("删除成功");
          this.init();
        });
    },
    handleUpdate: function(row, index, done, loading) {
      let totalScore = this.totalZjScoreData[0].ywc;
      let dqScore = this.totalZjScoreData[0].yfp;
      if (undefined != this.oldEditRow) {
        dqScore = dqScore - this.oldEditRow.score;
      }
      if (undefined != dqScore) {
        dqScore = parseInt(dqScore);
      }

      let score = row.score;
      if (undefined != score) {
        score = parseInt(score);
      }

      if (dqScore + score > totalScore) {
        this.$message.error("分配积分不能大于剩余可分配积分");
        loading();
        return false;
      }

      let rowScore = row.ytj;
      if (row.score < row.ytj) {
        this.$message.error("修改积分包分值不能小于已提交分值");
        return false;
      }

      putObj(row)
        .then(data => {
          this.$message.success("修改成功");
          done();
          this.init();
        })
        .catch(() => {
          loading();
        });
    },
    handleSave: function(row, done, loading) {
      row.agentTypeId = 2;
      row.taskRuleId = this.taskRuleId;
      if (undefined == this.taskRuleId || this.taskRuleId == 0) {
        this.$message.error("请选择规则月份");
        return false;
      }

      let totalScore = this.totalZjScoreData[0].ywc;
      let dqScore = this.totalZjScoreData[0].yfp;
      if (undefined != dqScore) {
        dqScore = parseInt(dqScore);
      }

      let score = row.score;
      if (undefined != score) {
        score = parseInt(score);
      }

      if (dqScore + score > totalScore) {
        this.$message.error("分配积分不能大于剩余可分配积分分");
        loading();
        return false;
      }

      addObj(row)
        .then(data => {
          this.$message.success("添加成功");
          done();
          this.init();
        })
        .catch(() => {
          loading();
        });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    refreshChange() {
      this.getList(this.page);
      this.getTotalTableData();
    },
    getObjDept1() {
      let deptId = this.userInfo.deptId;
      getObjDept(deptId)
        .then(data => {
          var deptInfo = data.data.data;
          if (deptInfo.level == 3) {
            this.entLevel = 1;
            this.socreShtgTxt = "已提交";
          }

          if (deptInfo.level == 4) {
            this.entLevel = 2;
            this.socreShtgTxt = "已收到";
          }
        })
        .catch(() => {});
    },
    zzAdudit(row, index, done, loading) {
      let that = this;
      this.$confirm("终止后则该任务积分全部作废", "警告", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      }).then(function() {
        row.enableFlag = "1";
        row.packageStatus = "4";
        putObj(row)
          .then(data => {
            this.$message.success("任务终止成功");
          })
          .catch(() => {})
          .then(() => {
            that.$message.success("任务终止成功");
            that.init();
          });
      });
    },
    renderTaskPage() {
      this.$router.push({ path: "/admin/wmtask/indexJxs" });
    },

    beforeOpen(show, type) {
      let obj = tableOptionFp2;
      obj.addTitle = "";
      obj.editTitle = "";
      let objS = 0;
      let totalScore = this.totalZjScoreData[0].ywc;
      let dqScore = this.totalZjScoreData[0].yfp;
      objS = totalScore - dqScore;
      if (objS < 0) {
        objS = 0;
      }
      this.syScore = objS;

      window.boxType = type;

      show();
    }
  }
};
</script>
