<!--  -->
<template>
  <div class="Big-Book-table" v-if="curQue">
    <div class="Big-Book-Single-content">
      <div class="adult-book-input-item">
        <span class="adult-book-lable">标题：</span>   
        <el-input
          type="textarea"
          class="adult-book-input"
          :autosize="{ minRows: 2 }"
          placeholder="请输入标题"
          v-model="curQue.title"
          @blur="curQue.title = curQue.title.trim()"
          maxlength="500"
          show-word-limit
        ></el-input>
      </div>
      <div
        class="Big-Book-main"
        style="border-bottom: 1px #ccc solid; margin-bottom: 20px"
      >
        <div class="adult-book-input-item">
          <span class="adult-book-lable">表头：</span>
          <el-radio-group v-model="curQue.isHeader" @change="changeHeader"
            >     
            <el-radio :label="true">有</el-radio>
            <el-radio :label="false">无</el-radio>
          </el-radio-group>
        </div>
        <div class="adult-book-input-item">
          <span class="adult-book-lable">对齐方式：</span>
          <el-radio-group v-model="curQue.align"
            >     
            <el-radio label="left">左对齐</el-radio>
            <el-radio label="center">居中对齐</el-radio>
            <el-radio label="right">右对齐</el-radio>
          </el-radio-group>
        </div>
        <template v-if="curQue.isHeader">
          <div
            class="adult-book-input-item"
            v-for="(item, i) in curQue.headerList"
            :key="i"
          >
            <span class="adult-book-lable">表头{{ i + 1 }}：</span>           
             <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="item.con"
              class="adult-book-input"
              :autosize="{ minRows: 2 }"
              @blur="item.con = item.con.trim()"
              maxlength="200"
              show-word-limit
            ></el-input>
            <img
              @click="deleteHeader(i)"
              class="close"
              src="../../../assets/adult/del-close.png"
              alt=""
            />
          </div>
          <div class="addoption" @click="addHeader">添加表头</div>
        </template>
        <table style="table-layout: fixed">
          <tr v-if="curQue.headerList.length > 0 && curQue.isHeader">
            <th
              :class="'th' + heai"
              v-for="(item, heai) in curQue.headerList"
              :key="heai + 'header'"
            >
              {{ item.con }}
            </th>
          </tr>
          <tr v-for="(item, rowi) in curQue.option" :key="rowi + 'row'">
            <td
              :class="'td' + coli"
              v-for="(it, coli) in item"
              :key="coli + 'col'"
            >
              <el-button
                v-if="!it.ByMerge"
                size="small"
                @click="editTd(rowi, coli)"
                >编辑</el-button
              >
              <!-- <el-button
                size="small"
                type="primary"
                @click="removeTd(rowi, coli)"
                >删除</el-button
              > -->
              <!-- <template v-if="coli == item.length - 1"> 删除列 </template> -->
              <div>
                <el-button
                  style="position: absolute; top: 50px; left: 15px"
                  size="mini"
                  v-if="rowi == curQue.option.length - 1"
                  @click="removeCol(coli)"
                  >删除列</el-button
                >
              </div>
            </td>
            <el-button size="small" @click="removeRow(rowi)">删除行</el-button>
          </tr>
        </table>
        <div class="add">
          <div class="addoption" @click="addRow">增加行</div>
          <div class="addoption" v-if="!curQue.isHeader" @click="addCol">
            增加列
          </div>
        </div>
        <div class="adult-book-input-item">
          请输入每一列的宽度占比,最多为100,最少为0
        </div>
        <div
          class="adult-book-input-item"
          v-for="(item, i) in curQue.colWidthList"
          :key="'Colwid' + i"
        >
          <span class="adult-book-lable">第{{ i + 1 }}列</span>
           <el-input
            type="textarea"
            placeholder="请输入列的宽度"
            v-model="item.width"
            class="adult-book-input"
            :autosize="{ minRows: 2 }"
            @blur="item.width = item.width.trim()"
            maxlength="50"
            show-word-limit
          ></el-input>
        </div>
        <div class="adult-book-input-item">
          <span class="adult-book-lable">提示标题：</span>           
          <el-input
            type="textarea"
            class="adult-book-input"
            :autosize="{ minRows: 2 }"
            placeholder="请输入提示标题"
            v-model="curQue.hintTitle"
            @blur="curQue.hintTitle = curQue.hintTitle.trim()"
            maxlength="200"
            show-word-limit
          ></el-input>
        </div>
        <div
          v-for="(item, htindex) in curQue.hintOtion"
          :key="'hint' + htindex"
        >
          <div class="adult-book-input-item">
            <span class="adult-book-lable">提示选项：</span>           
            <el-input
              type="textarea"
              class="adult-book-input"
              :autosize="{ minRows: 2 }"
              placeholder="请输入提示内容"
              v-model="item.con"
              @blur="item.con = item.con.trim()"
              maxlength="200"
              show-word-limit
            ></el-input>
            <img
              @click="deleteHint(htindex)"
              class="close"
              src="../../../assets/adult/del-close.png"
              alt=""
            />
          </div>
          <div class="adult-book-input-item">
            <span class="adult-book-lable">选项拼音：</span>           
            <el-input
              type="textarea"
              class="adult-book-input"
              :autosize="{ minRows: 2 }"
              placeholder="请输入选项拼音"
              v-model="item.pinyin"
              @blur="item.pinyin = item.pinyin.trim()"
              maxlength="200"
              show-word-limit
            ></el-input>
            <el-button @click="getPinyin(item)">生成拼音</el-button>
          </div>
        </div>

        <div class="addoption" @click="addHint">添加选项</div>
      </div>
    </div>
    <el-dialog
      title="编辑内容"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      destroy-on-close
    >
      <template v-if="data">
        <div class="adult-book-input-item">
          <span class="adult-book-lable">内容：</span>
          <el-input
            type="textarea"
            class="adult-book-input"
            :autosize="{ minRows: 2 }"
            placeholder="请输入内容"
            v-model="data.con"
            @blur="data.con = data.con.trim()"
            maxlength="500"
            show-word-limit
          ></el-input>
        </div>
        <!-- <div
          class="Big-Book-con"
          v-for="(item, i) in data.answerList"
          :key="i + 'answer'"
        >
          <span>答案：</span>           
          <el-input
            style="width: 300px"
            type="textarea"
            autosize
            placeholder="请输入答案"
            v-model="item.answer"
            @blur="item.answer = item.answer.trim()"
          ></el-input>
          <img
            @click="deleteAnswer(data, i)"
            class="close"
            src="../../../assets/adult/del-close.png"
            alt=""
          />
        </div>
        <div class="addoption" @click="addAnswer(data)">增加答案</div>
        <div class="Big-Book-con">
          <span>合并单元格：</span>      
          <el-radio-group
            v-model="data.MergeDirection"
            @change="changeMergeDirection"
            >     
            <el-radio label="bottom">向下合并</el-radio>
            <el-radio label="right">向右合并</el-radio>
            <el-radio label="false">不合并</el-radio>
          </el-radio-group>
        </div>
        <div class="Big-Book-con">
          <span>是否需要录音：</span>           
          <el-radio v-model="data.isRecord" :label="true">是</el-radio>
          <el-radio v-model="data.isRecord" :label="false">否</el-radio>
        </div>
        <div
          class="Big-Book-con"
          v-if="mergeList.length > 0 && data.MergeDirection != 'false'"
        >
          <span>合并数量：</span>
          <el-select
            placeholder="请选择"
            v-model="data.mergeNumber"
            @change="changemMergeNumber"
          >
            <el-option
              v-for="item in mergeList"
              :key="item + 'a'"
              :value="item"
            >
            </el-option>
          </el-select>
        </div>
        <div class="Big-Book-mp3" v-if="data">
          <span>音频：</span>
          <Upload
            :changeFillId="changeMp3"
            :datafileList="data.mp3_list"
            :filleNumber="mp3Number"
            :uploadType="'mp3'"
          />
        </div> -->
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Upload from "../common/Upload.vue";
export default {
  name: "tableView",
  props: ["curQue", "fn_data", "changeCurQue"],
  components: { Upload },
  data() {
    return {
      form: {
        stem: {
          con: "",
          pinyin: "",
          english: "",
          highlight: "",
          underline: "",
          img_url: [],
          mp3_url: [],
        },
      },
      dialogVisible: false,
      data: null,
      rowIndex: null,
      colIndex: null,
      mp3Number: 1,
      mergeList: [],
      currentOption: null,
      data_structure: {
        type: "table",
        name: "表格",
        title: "",
        isHeader: false,
        align: "center",
        headerList: [
          {
            con: "",
          },
        ],
        option: [
          [
            {
              img_list: [],
              mp3_list: [],
              answerList: [
                {
                  answer: "",
                },
              ],
              con: "",
              MergeDirection: "false", //合并方向
              isRecord: false,
              ByMerge: false, //是否被合并
            },
          ],
        ],
        colWidthList: [
          {
            width: "",
          },
        ], // 每一列的宽度
        img_list: [],
        hintTitle: "",
        hintOtion: [
          {
            con: "",
            pinyin: "",
          },
        ],
      },
    };
  },
  computed: {},
  watch: {},
  //方法集合
  methods: {
    // 点击生成拼音
    getPinyin(item) {
      let bool = false;
      let value = "";
      if (item.con == "") {
        this.$message.warning("请先输入内容,再生成拼音");
        bool = true;
      } else {
        value = item.con;
      }
      if (bool) {
        return;
      }
      let result = pinyinUtil.getPinyin(value);
      item.pinyin = result;
      this.$forceUpdate();
    },
    // 删除提示选项
    deleteHint(index) {
        this.$confirm("确定要删除吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
        .then(() => {
            if (this.curQue.hintOtion.length <= 1) {
                this.$message.warning("至少要保留一个选项");
                return;
            }
            this.curQue.hintOtion.splice(index, 1);
        })
    },
    // 增加提示选项
    addHint() {
      let obj = JSON.parse(JSON.stringify(this.data_structure.hintOtion[0]));
      this.curQue.hintOtion.push(obj);
    },
    // 修改表头时清空option否则引发bug
    changeHeader(val) {
      let obj = JSON.parse(JSON.stringify(this.data_structure.option));
      this.curQue.option = obj;
    },
    // 选择合并方向或者不合并
    changeMergeDirection(val) {
      if (val == "bottom") {
        let num = this.currentOption.length - 1 - this.rowIndex;
        for (let i = 1; i <= num; i++) {
          this.mergeList.push(i);
        }
      }
      if (val == "false") {
        let currentTd = this.curQue.option[this.rowIndex][this.colIndex];
        if (currentTd.MergeDirection == "bottom") {
          this.currentOption.forEach((item, row) => {
            item.forEach((it, col) => {
              if (
                col == this.colIndex &&
                row > this.rowIndex &&
                row <= this.rowIndex + currentTd.mergeNumber
              ) {
                it.ByMerge = false;
              }
            });
          });
        }
      }
    },
    // 选择合并数量
    changemMergeNumber(val) {
      this.currentOption.forEach((item, row) => {
        item.forEach((it, col) => {
          if (
            col == this.colIndex &&
            row > this.rowIndex &&
            row <= this.rowIndex + val
          ) {
            it.ByMerge = true;
          }
        });
      });
    },
    //   上传音频
    changeMp3(fileList) {
      const articleImgList = JSON.parse(JSON.stringify(fileList));
      const articleImgRes = [];
      articleImgList.forEach((item) => {
        if (item.response) {
          const obj = {
            name: item.name,
            url: item.response.file_info_list[0].file_url,
            id: "[FID##" + item.response.file_info_list[0].file_id + "##FID]",
            media_duration: item.response.file_info_list[0].media_duration, //音频时长
          };
          articleImgRes.push(obj);
        }
      });
      this.data.mp3_list = JSON.parse(JSON.stringify(articleImgRes));
    },
    //   删除答案
    deleteAnswer(data, index) {
      if (data.answerList.length <= 1) {
        this.$message.warning("至少要保留1个答案");
        return;
      }
      data.answerList.splice(index, 1);
    },
    // 增加答案
    addAnswer(data) {
      let type = this.curQue.type;
      let cur_fn_data_arr = this.fn_data.filter((item) => item.type == type);
      let cur_fn_data = JSON.parse(JSON.stringify(cur_fn_data_arr[0]));
      let obj = cur_fn_data.data_structure.option[0][0].answerList[0];
      data.answerList.push(obj);
    },
    //   删除行
    removeRow(index) {
        this.$confirm("确定要删除吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
        .then(() => {
            if (this.curQue.option.length <= 1) {
                this.$message.warning("至少要保留一行");
                return;
            }
            this.curQue.option.forEach((item, i) => {
                if (i == index) {
                this.curQue.option.splice(i, 1);
                }
            });
        })
    },
    // 删除列
    removeCol(index) {
        this.$confirm("确定要删除吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
        .then(() => {
            if (this.curQue.option[0].length <= 1) {
                this.$message.warning("至少要保留一列");
                return;
            }
            this.curQue.option.forEach((item) => {
                item.forEach((it, i) => {
                if (i == index) {
                    item.splice(i, 1);
                }
                });
            });
            this.curQue.headerList.forEach((item, i) => {
                if (i == index) {
                this.curQue.headerList.splice(i, 1);
                }
            });
            this.curQue.colWidthList.splice(index, 1);
        })
    },
    //   删除td
    removeTd(rowi, coli) {
      console.log(rowi, coli);
    },
    // 编辑td
    editTd(rowi, coli) {
      this.rowIndex = rowi;
      this.colIndex = coli;
      this.data = JSON.parse(JSON.stringify(this.curQue.option[rowi][coli]));
      this.dialogVisible = true;
      this.currentOption = null;
      this.currentOption = JSON.parse(JSON.stringify(this.curQue.option));
      if (this.data.MergeDirection == "false") {
        this.mergeList = [];
      }
    },
    // 保存
    save() {
      this.curQue.option = JSON.parse(JSON.stringify(this.currentOption));
      this.curQue.option[this.rowIndex][this.colIndex] = JSON.parse(
        JSON.stringify(this.data)
      );
      this.dialogVisible = false;
    },
    //   增加行
    addRow() {
      let obj = JSON.parse(JSON.stringify(this.data_structure.option[0][0]));
      let arr = [];
      for (let i = 0; i < this.curQue.option[0].length; i++) {
        arr.push(obj);
      }
      this.curQue.option.push(arr);
    },
    //   增加列
    addCol() {
      let obj = JSON.parse(JSON.stringify(this.data_structure.option[0][0]));
      let widthObj = JSON.parse(
        JSON.stringify(this.data_structure.colWidthList[0])
      );
      this.curQue.colWidthList.push(widthObj);
      this.curQue.option.forEach((item, i) => {
        item.push(obj);
      });
    },
    // 删除其中一个表头
    deleteHeader(index) {
        this.$confirm("确定要删除吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
        .then(() => {
            if (this.curQue.headerList.length <= 1) {
                this.$message.warning("至少要保留一个表头");
                return;
            }
            this.curQue.headerList.splice(index, 1);
            this.curQue.option.forEach((item) => {
                item.splice(index, 1);
            });
            this.curQue.colWidthList.splice(index, 1);
        })
    },
    //添加一个表头
    addHeader() {
      let optionobj = JSON.parse(
        JSON.stringify(this.data_structure.headerList[0])
      );
      this.curQue.headerList.push(optionobj);
      let obj = JSON.parse(JSON.stringify(this.data_structure.option[0][0]));
      this.curQue.option.forEach((item) => {
        item.push(obj);
      });
      let widthObj = JSON.parse(
        JSON.stringify(this.data_structure.colWidthList[0])
      );
      this.curQue.colWidthList.push(widthObj);
    },
    // 关闭弹窗并清空数据
    handleClose() {
      this.dialogVisible = false;
      this.data = null;
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    if (!this.curQue) {
      this.changeCurQue(this.data_structure);
    } else {
      // if (!this.curQue.colWidthList) {
      //   let colWidthList = [];
      //   this.curQue.option[0].forEach((item) => {
      //     let widthObj = JSON.parse(
      //       JSON.stringify(this.data_structure.colWidthList[0])
      //     );
      //     colWidthList.push(widthObj);
      //   });
      //   this.curQue.colWidthList = colWidthList;
      //   this.$forceUpdate()
      // }
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scope>
//@import url(); 引入公共css类
.Big-Book-table {
  &-content {
    &.m {
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
    }

    .Big-Book-title {
      font-size: 16px;
      line-height: 40px;
      color: #000;
      margin-right: 15px;
    }
  }
  .Big-Book-main {
    > div {
      margin-bottom: 10px;
      &.Big-Book-pinyin {
        display: flex;
        justify-content: flex-start;
        align-items: center;
      }
    }
  }
  .addoption {
    width: 150px;
    height: 40px;
    left: 40px;
    top: 304px;
    background: #f3f3f3;
    border: 1px dashed rgba(0, 0, 0, 0.15);
    box-sizing: border-box;
    border-radius: 4px;
    text-align: center;
    line-height: 40px;
    cursor: pointer;
    margin-right: 20px;
  }
  .Big-Book-divide {
    > div {
      width: 100%;
    }
    .answerList {
      > div {
        margin-top: 16px;
        display: flex;
        align-items: center;
        > :nth-child(1) {
          display: inline-block;
          width: 100px;
          margin-right: 10px;
          word-break: break-all;
        }

        .checkbox-group {
          > span {
            display: inline-block;
            margin-left: 29px;
          }
        }
      }
    }
  }
  .Big-Book-con {
    display: flex;
    align-items: center;
    margin: 15px 0;
    img {
      width: 24px;
      height: 24px;
      cursor: pointer;
    }
  }
  .Big-Book-mp3 {
    display: flex;
  }
  .add {
    display: flex;
    margin-top: 50px;
  }
  table {
    tr {
      th {
        min-width: 100px;
        max-width: 100px;
        min-height: 40px;
        max-height: 40px;
        border: 1px solid black;
        text-align: center;
        padding: 5px;
        word-break: break-all;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      td {
        min-width: 100px;
        max-width: 100px;
        height: 42px;
        border: 1px solid black;
        text-align: center;
        padding: 5px;
        word-break: break-all;
        position: relative;
      }
      display: flex;
      align-items: center;
    }
  }
}
</style>