<template>
  <div class="context">
    <el-page-header @back="goBack" content="动作分组管理"></el-page-header>
    <div class="panel">
      <br>
      <h5> {{ actionName }}</h5>
    </div>
    <div class="change">
      <el-button @click="addAction" size="mini" type="primary" v-show="enableAdd">添加动作</el-button>
      <el-button @click="deleteAction" 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
                element-loading-background="rgba(0, 0, 0, 0.8)"
                class @selection-change="handleSelectionChange" @current-change="clickChange"
                :row-class-name="tableRowClassName">
        >
        <el-table-column label="选择" width="55">
          <template slot-scope="scope">
            <el-radio v-model="tableRadio" :label="scope.row">
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column type="index" label="动作位序" align="center" width="80"/>
        <el-table-column prop="EaName" label="动作名称" align="center"/>
        <el-table-column prop="id" label="操作">
          <template slot-scope="scope">
            <el-button type="success" size="mini" @click="moveRow(scope.row,-1)"
                       v-if="scope.$index > 0">
              上移
            </el-button>
            <el-button type="warning" size="mini" @click="moveRow(scope.row,1)"
                       v-if="scope.$index < tableData.length-1">
              下移
            </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-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="checkBoxAllChange"
                           style="float:left; margin-left: 30px">全选
              </el-checkbox>
              <!--实际可选内容-->
              <el-checkbox-group v-model="checkedOptions" @change="checkBoxSingleChange"
                                 style="float:left; margin-left: 10px">
                <el-checkbox v-for="item in selectOptions" :label="item" :key="item.EaId" :value="item.EaId">
                  {{ item.EaName }}
                </el-checkbox>
              </el-checkbox-group>

            </el-form-item>

            <el-form-item label="身体动作" :required="true" v-show="false">
              <el-select v-model="form.action" value-key="EaId" placeholder="请选择" v-if="form.btnType == 0"
                         @change="selectAction">
                <el-option
                    v-for="item in form.eaList"
                    :key="item.EaId"
                    :label="item.EaName"
                    :value="item">
                </el-option>
              </el-select>
              <span v-if="form.btnType == 1">{{ form.bnName }}</span>
            </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 {
  ExerciseActionQuery,
  AGDetailBatchEdit,
  AGDetailQuery,
} from "../api/getApiRes";

let qs = require('qs');
export default {
  data() {
    return {
      agId: '',
      shopId: '',
      actionName: '',
      dialogVisible: false,//其他dialog
      addBodyNodeVisible: false,//新增关联动作弹窗
      dialogTitle: '',
      tableRadio: [],
      cur_page: 1,
      enableAdd: true,
      enableDelete: true,
      disablePush: true,
      //弹出框
      selectOptions: [],
      checkedOptions: [],
      checkAll: false,
      isIndeterminate: 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: {
        eaId: '',
        eaName: '',
        eaList: [],
        action: {},
        btnType: 0,//0新建，1编辑编辑
      },
      tableData: []
    }
  },
  mounted() {
    this.agId = this.$route.query.agId;
    this.actionName = this.$route.query.agName;
    this.shopId = this.$route.query.shopId;
    this.getTableQuery();
    this.getActions();
  },
  methods: {
    //返回上一页
    goBack() {
      this.$router.push({path: '/ratingManage'});
    },
    //顶部菜单项切换
    goType(url) {
      this.$router.push({path: '/' + url});
    },
    //tableData中的行点击事件
    clickChange(item) {
      this.tableRadio = item
    },
    //tableData中的行选择事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    tableRowClassName({row, rowIndex}) {
      row.index = rowIndex;
      // console.log(row, rowIndex);
    },
    // 关闭所有弹窗
    allDialogClose() {
      this.dialogVisible = false;
    },
    //清除弹窗输入项
    clearForm() {
      let that = this;
      that.form.eaId = '';
      that.form.eaName = '';
      that.form.action = '';
    },
    // 新增身体动作
    addAction() {
      this.clearForm();
      this.addBodyNodeVisible = true;
      this.form.btnType = 0;
      this.dialogTitle = '添加动作'
      this.getActions();
    },
    selectAction(val) {
      let that = this;
      that.form.eaId = val.EaId;
      that.form.eaName = val.EaName;
      that.form.action = val;
    },
    //checkBox全部选中事件
    checkBoxAllChange(val) {
      let checked = this.selectOptions.map(item => {
        return item;
      });
      this.checkedOptions = val ? checked : [];
      this.isIndeterminate = false;
    },
    //checkBox单个选中事件
    checkBoxSingleChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.selectOptions.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.selectOptions.length;
    },
    //确认提交新动作
    confirmAddNodeRelation() {
      let that = this;
      if (that.checkedOptions == null || that.checkedOptions.length < 1) {
        this.$message.error('错了哦，动作不能为空');
        return false
      }
      for (let i in that.checkedOptions) {
        that.tableData.push(that.checkedOptions[i]);
      }
      this.addBodyNodeVisible = false;
      this.checkedOptions = [];//清空已选中
      this.checkAll = false;//清空已选中
      that.disablePush = false;
    },
    //删除关联动作
    deleteAction() {
      let that = this;
      if (that.tableRadio === null || that.tableRadio.length == 0) {
        that.$message.error("请先选中一条记录");
        return false
      }
      this.$confirm('此操作将删除身体动作, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let row = that.tableRadio;
        for (let i in that.tableData) {
          if (row.index == i) {
            that.tableData.splice(i, 1);
          }
        }
        that.disablePush = false;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //设置行等级变动事件
    handleChange() {
      let that = this;
      that.disablePush = false;
    },
    //提交本页数据
    postPageData() {
      let that = this;

      //拼接要提交的数据
      let actionRs = [];
      for (let i = 0; i < that.tableData.length; i++) {//遍历table中的人员名单
        let thisRow = {};
        thisRow.index = that.tableData[i].index;
        // thisRow.AgId = that.tableData[i].AgId;
        thisRow.AgdId = that.tableData[i].AgdId;
        thisRow.EaId = that.tableData[i].EaId;
        thisRow.EaName = that.tableData[i].EaName;
        actionRs.push(thisRow);
      }
      console.log(JSON.stringify(actionRs))
      let param = {
        token: localStorage.token,
        agId: that.agId,
        agName: that.actionName,
        agdRs: JSON.stringify(actionRs)
      };
      console.log(JSON.stringify(param));
      let postData = qs.stringify(param);
      AGDetailBatchEdit(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;
    },
    //设置行状态 1:后移 -1:前移
    moveRow(row, status) {
      let that = this;

      for (let i = 0; i < that.tableData.length; i++) {
        if (i == row.index) {
          if (i + status < 0 || i + status > that.tableData.length - 1) {
            console.log(false);
            return false;
          }

          if (status == 1) {//后移
            let temp = deepClone(that.tableData[i + 1])
            that.tableData[i + 1] = deepClone(that.tableData[i]);
            that.tableData[i] = deepClone(temp);
          }

          if (status == -1) {//后移
            let temp = deepClone(that.tableData[i - 1])
            that.tableData[i - 1] = deepClone(that.tableData[i]);
            that.tableData[i] = deepClone(temp);
          }
        }
      }
      that.disablePush = false;
    },
    ////获取当前动作可绑定节点
    getActions() {
      let that = this;
      that.loading = true;
      let param = {
        token: localStorage.token,
        shopId: localStorage.shopId,
        agId: 0,
        status: 1
      };
      let postData = qs.stringify(param);
      ExerciseActionQuery(postData).then(res => {
        let json = res;
        if (json.Code == 0) {
          if (json.Rs.length > 0) {
            that.form.eaList = json.Rs;
            that.selectOptions = json.Rs;
            that.enableAdd = true;
          } else {
            that.form.eaList = [];
            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,
        shopId: that.shopId,
        agId: that.agId
      };
      let postData = qs.stringify(param);
      AGDetailQuery(postData).then(res => {
        let json = res;
        if (json.Code == 0) {
          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.disablePush = true;
        } 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 == '/actionGroupManage') {
        this.agId = this.$route.query.agId;
        this.actionName = this.$route.query.agName;
        this.shopId = this.$route.query.shopId;
        this.getTableQuery();
        this.getActions();
      }
    },
  },
}
</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>