<template>
  <div class="context">
    <el-page-header @back="goBack" content="动作管理"></el-page-header>
    <div class="panel">
      <br>
      <h5> {{ eaName }}</h5>
    </div>
    <div class="change">
      <el-button @click="addBodyNode" size="mini" type="primary" v-show="enableAdd">新增节点</el-button>
      <el-button @click="editBodyNode" size="mini" v-show="false">编辑节点</el-button>
      <el-button @click="deleteBodyNode" size="mini" type="danger" v-show="enableDelete">删除节点</el-button>
      <el-button @click="postPageData" size="mini" style="float: right;" v-bind:disabled="disablePush">提交</el-button>
    </div>
    <div class="table">
      <el-table :data="tableData" border is-horizontal-resize
                :default-sort="{ prop: 'date', order: 'descending' }" element-loading-background="rgba(0, 0, 0, 0.8)"
                class @selection-change="handleSelectionChange" @current-change="clickChange">
        >
        <el-table-column label="选择" width="55">
          <template slot-scope="scope">
            <el-radio v-model="tableRadio" :label="scope.row">
              <i></i>
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" align="center" width="60"/>
        <el-table-column prop="BnName" label="节点名称" align="center" sortable/>
        <el-table-column prop="Weight" label="权重等级" align="center" sortable>
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.Weight" @change="handleChange" :min="0" :max="3"
                             label="一级"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column prop="DefScore" label="权重分数" align="center" sortable>
          <template slot-scope="scope">
            {{ scope.row.DefScore }}
          </template>
        </el-table-column>
        <!--        <el-table-column prop="id" label="状态">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-button type="success" v-if="scope.row.Status == 8" size="mini" @click="enableRow(scope.row,1)">-->
        <!--              启用-->
        <!--            </el-button>-->
        <!--            <el-button type="warning" v-if="scope.row.Status == 1" size="mini" @click="enableRow(scope.row,8)">-->
        <!--              禁用-->
        <!--            </el-button>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
      <br/>
      <el-pagination background :total="pagination.total" :page-size="pagination.pageItem"
                     @current-change="pageChange"
                     :current-page.sync="cur_page"
                     v-show="false"
      />
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="addBodyNodeVisible" width="650px">
      <div class="dialogContent">
        <div class>
          <el-form ref="form" :model="form" label-width="160px">
            <el-form-item label="身体节点" :required="true">
              <el-select v-model="form.bnId" placeholder="请选择" v-if="form.btnType == 0">
                <el-option
                    v-for="item in form.bnList"
                    :key="item.BnId"
                    :label="item.BnName"
                    :value="item.BnId">
                </el-option>
              </el-select>
              <span v-if="form.btnType == 1">{{ form.bnName }}</span>

            </el-form-item>
            <el-form-item label="权重" v-if="form.btnType == 1">
              <el-input-number v-model="form.weight" :min="0" :max="3"></el-input-number>
            </el-form-item>
            <!--            <el-form-item label="默认分数">-->
            <!--              <el-input-number v-model="form.score" :min="1" :max="10" label="描述文字"></el-input-number>-->
            <!--            </el-form-item>-->
          </el-form>
        </div>
      </div>
      <div class="dialogFooter">
        <el-button type="primary" size="small" v-if="form.btnType == 0" @click="confirmAddNodeRelation">确定</el-button>
        <el-button type="primary" size="small" v-if="form.btnType == 1" @click="confirmEditRelation">确定</el-button>
        <el-button size="small" @click="addBodyNodeVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Global from '../Global.js'
import {
  ENRelationEdit,
  ENRelationQuery,
  ENRelationAdd,
  BodyNodeQuery,
  ENRelationStatusEdit,
  ENRelationBatchEdit,
} from "../api/getApiRes";

let qs = require('qs');
export default {
  data() {
    return {
      eaId: '',
      eaName: '',
      dialogVisible: false,//其他dialog
      addBodyNodeVisible: false,//新增关联节点弹窗
      dialogTitle: '',
      tableRadio: [],
      cur_page: 1,
      enableAdd: true,
      enableDelete: true,
      disablePush: true,
      // panel 配置项目
      panel: {
        str: '',
        status: "",
        draw: 1,
        start: 0,
        recordsTotal: 0,
        tableData: [],
        allTableData: [],
        loading: false,
        statusOptions: [
          {value: "", label: '全部'},
          {value: 1, label: '启用'},
          {value: 8, label: '禁用'},
        ]
      },
      multipleSelection: [],
      pagination: {
        pageItem: 200,
        pageOptions: pageOptions(),
        total: 100,
        pageIndex: 1,
      },
      form: {
        enId: '',
        bnId: '',
        bnName: '',
        bnList: [],
        weight: 0,
        score: 0,
        btnType: 0,//0新建，1编辑编辑
      },
      tableData: []
    }
  },
  mounted() {
    console.log("mounted");
    this.eaId = this.$route.query.eaId;
    this.eaName = this.$route.query.eaName;
    this.getTableQuery();
    this.getBodyNodes();
  },
  methods: {
    //返回上一页
    goBack() {
      this.$router.push({path: '/actionExercise'});
    },
    //顶部菜单项切换
    goType(url) {
      this.$router.push({path: '/' + url});
    },
    //tableData中的行点击事件
    clickChange(item) {
      this.tableRadio = item
    },
    //tableData中的行选择事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 关闭所有弹窗
    allDialogClose() {
      this.dialogVisible = false;
    },
    //清除弹窗输入项
    clearForm() {
      this.form.bnId = '';
    },
    // 新增身体节点
    addBodyNode() {
      this.clearForm();
      this.addBodyNodeVisible = true;
      this.form.btnType = 0;
      this.dialogTitle = '新增关联节点'
      this.getBodyNodes();
    },
    //确认提交新动作
    confirmAddNodeRelation() {
      let that = this;
      if (!that.form.bnId) {
        this.$message.error('错了哦，身体节点名称不能为空');
        return false
      }
      console.log(that.form.bnId);
      let param = {
        token: localStorage.token,
        eaId: that.eaId,
        eaName: that.eaName,
        bnId: that.form.bnId,
        bnName: "bodyNode:" + that.form.bnId,
        weight: that.form.weight,
        defScore: that.form.score
      };
      let postData = qs.stringify(param);
      ENRelationAdd(postData).then(res => {
        let json = res;
        if (json.Code == 0) {
          // 关闭弹窗
          that.addBodyNodeVisible = false;
          // 重载列表
          that.getTableQuery();
          that.$message({
            showClose: true,
            message: '关联节点添加成功！',
            type: 'success'
          });
          that.getTableQuery();
          if (that.form.bnList.length === 1) {
            that.enableAdd = false;
          }
        } else {
          that.$message.error(json.Memo + ' 错误码：' + json.Code);
        }
      })
    },
    //编辑关联节点
    editBodyNode() {
      let that = this;
      this.clearForm();
      if (this.tableRadio == null) {
        this.$message.error("请先选中一条记录");
        return false
      }
      this.dialogVisible = true;
      this.addBodyNodeVisible = true
      this.dialogTitle = '编辑节点';

      let row = this.tableRadio;
      this.form.shopid = row.ShopId;
      this.form.bnId = row.BnId;
      this.form.enId = row.EnId;
      this.form.weight = row.Weight;
      this.form.bnName = row.BnName;
      this.form.btnType = 1;
    },
    //提交编辑关联节点
    confirmEditRelation() {
      let that = this;
      // if (!that.form.name) {
      //   this.$message.error('错了哦，关联节点名称不能为空');
      //   return false
      // }

      let param = {
        token: localStorage.token,
        enId: that.form.enId,
        eaName: that.eaName,
        bnId: that.form.bnId,
        bnName: that.form.name,
        weight: that.form.weight,
        defScore: that.form.score
      };
      let postData = qs.stringify(param);
      ENRelationEdit(postData).then(res => {
        let json = res;
        if (json.Code == 0) {
          // 关闭弹窗
          that.addBodyNodeVisible = false;
          // 重载列表
          that.getTableQuery();
          that.$message({
            showClose: true,
            message: '身体节点编辑信息编辑成功！',
            type: 'success'
          });
        } else {
          that.$message.error(json.Memo + ' 错误码：' + json.Code);
        }
      })
    },
    //删除关联节点
    deleteBodyNode() {
      let that = this;
      if (that.tableRadio === null) {
        that.$message.error("请先选中一条记录");
        return false
      }
      let row = that.tableRadio;
      let param = {
        token: localStorage.token,
        bnId: row.BnId,
        bnName: row.BnName,
        enId: row.EnId,
        eaName: that.eaName,
        status: 9 //1：启用，8：禁用，9：删除
      };
      let postData = qs.stringify(param);

      this.$confirm('此操作将永久删除关联的身体节点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ENRelationStatusEdit(postData).then(res => {
          let json = res;
          if (json.Code == 0) {
            // table 重载
            that.getTableQuery();
            that.$message({
              showClose: true,
              message: '删除成功',
              type: 'success'
            });
            that.enableAdd = true;
          } else {
            that.$message.error(json.Memo);
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //设置行等级变动事件
    handleChange() {
      let that = this;
      that.disablePush = false;

      //计算每个动作节点的权重分数 一级权重：1/二级权重：1.5/三级权重：2
      //首先计算出单位权重比例的分数
      let sumWeight = 0, perWeightScore = 0.00;
      for (let i = 0; i < that.tableData.length; i++) {//遍历table
        console.log(JSON.stringify(that.tableData[i]));
        if (that.tableData[i].Weight > 0) {
          if (that.tableData[i].Weight == 1) {
            sumWeight += 1;
          }
          if (that.tableData[i].Weight == 2) {
            sumWeight += 1.5;
          }
          if (that.tableData[i].Weight == 3) {
            sumWeight += 2;
          }
        }
      }
      perWeightScore = 100 / sumWeight;
      //还原到每个动作节点的分数中
      let perWeight = 1;
      for (let i = 0; i < that.tableData.length; i++) {//遍历table
        console.log(JSON.stringify(that.tableData[i]));
        if (that.tableData[i].Weight == 0) {
          perWeight = 0;
        }
        if (that.tableData[i].Weight == 1) {
          perWeight = 1;
        }
        if (that.tableData[i].Weight == 2) {
          perWeight = 1.5;
        }
        if (that.tableData[i].Weight == 3) {
          perWeight = 2;
        }
        that.tableData[i].DefScore = (perWeight * perWeightScore).toFixed(2);
      }
    },
    //提交本页数据
    postPageData() {
      let that = this;

      //拼接要提交的数据
      let scoreRs = [];
      for (let i = 0; i < that.tableData.length; i++) {//遍历table中的人员名单
        console.log(i,JSON.stringify(that.tableData[i]));
        let thisRow = {};
        thisRow.EnId = that.tableData[i].EnId;
        thisRow.Weight = that.tableData[i].Weight;
        thisRow.DefScore = that.tableData[i].DefScore;
        scoreRs.push(thisRow);
      }
      let param = {
        token: localStorage.token,
        eaId: that.eaId,
        eaName: that.eaName,
        BodyNodeRs: JSON.stringify(scoreRs)
      };
      console.log(JSON.stringify(param));
      let postData = qs.stringify(param);
      ENRelationBatchEdit(postData).then(res => {
        let json = res;
        if (json.Code == 0) {
          that.$message({
            showClose: true,
            message: '执行成功！',
            type: 'success'
          });
          // table 重载
          that.getTableQuery();
        } else {
          that.$message.error(json.Memo + ' 错误码：' + json.Code);
        }
      })

      that.disablePush = true;
    },
    //设置行状态
    enableRow(row, status) {
      let that = this;
      let param = {
        token: localStorage.token,
        bnId: row.BnId,
        bnName: row.BnName,
        enId: row.EnId,
        eaName: that.eaName,
        status: status,//1：启用 8：暂停 9：删除
      };
      let postData = qs.stringify(param);
      ENRelationStatusEdit(postData).then(res => {
        let json = res;
        if (json.Code == 0) {
          that.$message({
            showClose: true,
            message: '执行成功！',
            type: 'success'
          });
          // table 重载
          that.getTableQuery();
        } else {
          that.$message.error(json.Memo + ' 错误码：' + json.Code);
        }
      })
    },
    ////获取当前动作可绑定节点
    getBodyNodes() {
      let that = this;
      that.loading = true;
      let param = {
        token: localStorage.token,
        eaId: that.eaId
      };
      let postData = qs.stringify(param);
      BodyNodeQuery(postData).then(res => {
        let json = res;
        if (json.Code == 0) {
          if (json.Rs.length > 0) {
            that.form.bnList = json.Rs;
            that.enableAdd = true;
          } else {
            that.form.bnList = [];
            that.enableAdd = false;
          }
          // 设置分页数据
          that.setPagination();
        } else {
          that.$message.error(json.Memo + ' 错误码：' + json.Code);
        }
      })
    },
    // 查询按钮
    query() {
      let that = this;
      that.start = 0;
      that.cur_page = 1;
      this.getTableQuery();
      this.$message.success('查询完毕');
    },
    // 页面数据查询
    getTableQuery() {
      let that = this;
      that.loading = true;
      let param = {
        token: localStorage.token,
        eaId: that.eaId
      };
      let postData = qs.stringify(param);
      ENRelationQuery(postData).then(res => {
        let json = res;
        if (json.Code == 0) {
          that.loading = false;
          if (json.Rs) {
            if (json.Rs.length == 0) {
              that.enableDelete = false;
            } else {
              that.enableDelete = true;
            }
            //不使用分页
            that.tableData = json.Rs;
            //分页
            // that.allTableData = json.Rs;
            // that.recordsTotal = json.Rs.length;

          } else {
            //不使用分页
            that.tableData = [];

            //使用分页
            // that.allTableData = [];
            // that.recordsTotal = 0;
          }
          // 设置分页数据
          that.setPagination();
        } else {
          that.$message.error(json.Memo + ' 错误码：' + json.Code);
        }
      })
    },
    // 设置分页数据
    setPagination() {
      // 分页属性
      let that = this;
      that.pagination.total = that.recordsTotal;

      // 默认分页
      that.tableData = that.allTableData.filter((item, index) => {
        return index < that.pagination.pageItem;
      });
    },
    // 每页显示数量
    handleSizeChange() {
      let that = this;
      that.tableData = that.allTableData.filter((item, index) => {
        return index < that.pagination.pageItem;
      });
      that.draw = that.pagination.pageItem;
      // that.getTableQuery();
    },
    // 翻页
    pageChange(pageIndex) {
      let that = this;
      // 获取当前页
      let index = that.pagination.pageItem * (pageIndex - 1);
      // 数据总数
      let nums = that.pagination.pageItem * pageIndex;
      // 容器
      let tables = [];
      for (var i = index; i < nums; i++) {
        if (that.allTableData[i]) {
          tables.push(that.allTableData[i])
        }
        this.tableData = tables;
      }
      that.start = index * that.draw;
      // that.getTableQuery();
    },
    // 自动排序
    sortChange(params) {
      console.log(params)
    },
    //            过滤时间
    filterFmtDate(value, row, column) {
      let that = this;
      if (column == 0) {
        return '未获得'
      } else {
        return nonTfmtDatetoLength(new Date(column * 1000), 16);
      }
    },
  },
  watch: {
    $route(to) {
      if (to.path == '/actionManage') {
        this.eaId = this.$route.query.eaId;
        this.eaName = this.$route.query.eaName;
        this.getTableQuery();
        this.getBodyNodes();
      }
    },
  },
}
</script>

<style scoped>
@import "../assets/css/panel.css";

.context {
  /* height: 770px; */
  overflow-y: scroll;

  display: block;
  margin: 0 auto;
  background-color: #fff !important;
  padding: 30px;
}

.panel-body {
  padding: 20px;
  background: #f0f2f5;
}

.change {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  padding-top: 10px;
  padding-bottom: 10px;
}

.change button {
  float: left;
}

.change button.pull-right {
  float: right;
}

.likeTab {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  padding-top: 10px;
  padding-bottom: 0;
  border-bottom: 1px solid #ccc;
  margin-bottom: 10px;
}

.likeTab button {
  float: left;
  border-radius: 0;
}

.likeTab button.pull-right {
  float: right;
}

.dialogTitle {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  color: #000000;
  font-size: 18px;
  text-align: center;
}

.dialogTitle em {
  float: none;
  font-style: normal;
  color: #3799ff;
  margin: 0;
}

/deep/ .el-transfer-panel__item .el-checkbox__input {
  left: 40px;
}

.dialogFooter {
  width: 90%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  margin-top: 10px;
}

.dialogFooter button {
  float: right;
  margin-left: 10px;
}

.dialogContent {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
}

.dialogContent .pull-left {
  width: 30%;
  float: left;
}

.dialogContent .pull-right {
  width: 70%;
  float: right;
}

.panel_control /deep/ .el-input {
  width: 90px;
  float: left;
}

.panel-body em {
  /*float: left;*/
  line-height: 40px;
  margin-right: 10px;
}

</style>