<template>
  <div class="box">
    <div style="width: 100%">
      <el-card class="elcard" style="border-radius: 15px">
        <div class="publiccss">项目模板</div>
        <el-table
          :data="tableData"
          style="width: 100%; margin-top: 20px"
          row-key="id"
          class="el-table__body-wrapper tbody"
          @row-click="rowclick"
          highlight-current-row
          height="300"
        >
          <el-table-column prop="id" label="编号" width="300">
          </el-table-column>
          <el-table-column prop="displayName" label="名称"> </el-table-column>
          <el-table-column prop="creatorName" label="创建者" width="130">
          </el-table-column>
          <el-table-column prop="creationTime" label="创建时间" width="200">
            <template slot-scope="scope">
              {{ scope.row.creationTime | dateFormat }}
            </template>
          </el-table-column>
          <el-table-column prop="lastModifierName" label="修改者" width="">
          </el-table-column>
          <el-table-column
            prop="lastModificationTime"
            label="修改时间"
            width="200"
          >
            <template slot-scope="scope">
              {{ scope.row.lastModificationTime | dateFormat }}
            </template>
          </el-table-column>
          <el-table-column prop="result" label="结果" width="">
          </el-table-column>
          <el-table-column label="操作" width="">
            <template>
              <el-tag
                class="move"
                style="cursor: move; margin-left: 15px"
                draggable="true"
              >
                <i
                  class="el-icon-d-caret"
                  style="width: 1rem; height: 1rem"
                ></i>
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <!-- <comp-table
          :tableData="tableData"
          :tableHeader="tableHeader"
          @clickevents="rowclick"
          ref="singleTable"
        >
        </comp-table> -->
        <div class="subjecttitle">
          <span style="margin-top: 10px; padding: 5px; margin-left: %"
            >项目类别</span
          >
          <el-select
            v-model="values"
            placeholder="请选择"
            @change="ischangs"
            style="margin-top: 5px"
          >
            <el-option
              v-for="item in projectid"
              :key="item.id"
              :label="item.displayName"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <span style="margin-left: 10%; padding: 5px">搜索选择</span>
          <el-select
            filterable
            v-model="flitvalues"
            placeholder="请选择"
            style="margin-top: 5px"
          >
            <el-option
              v-for="item in filetelists"
              :key="item.id"
              :label="item.displayName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
        <div class="mainbox">
          <div class="mainleftbox">
            <div class="weixuan">未选项目</div>
            <div
              v-for="(item, index) in leftdata"
              :key="index"
              @click="clickPaixu(item, index)"
              @dblclick="shuanji(item, index)"
              :class="num === index ? 'activetext' : ''"
              style=""
            >
              <div>{{ item.displayName }}</div>
            </div>
          </div>
          <div class="Selectbutton">
            <div style="margin-top: 10px">
              <el-button @click="addall"
                >全添加<i class="el-icon-caret-right"></i
                ><i class="el-icon-caret-right"></i
              ></el-button>
            </div>
            <div style="margin-top: 10px">
              <el-button @click="addobj" style="width: 111px"
                >添加<i class="el-icon-caret-right"></i>
              </el-button>
            </div>
            <div style="margin-top: 10px">
              <el-button @click="removeright" style="width: 111px"
                >移去<i class="el-icon-caret-left"></i>
              </el-button>
            </div>
            <div style="margin-top: 10px">
              <el-button @click="allclear"
                >全移去<i class="el-icon-caret-left"></i
                ><i class="el-icon-caret-left"></i>
              </el-button>
            </div>
          </div>
          <div class="mainleftbox">
            <div class="weixuan">已选项目</div>
            <div
              v-for="(item, index) in rightdata"
              :key="index"
              @click="rightindex(item, index)"
              @dblclick="rightdelite(item, index)"
              :class="nums === index ? 'activetext' : ''"
            >
              <div>{{ item.displayName }}</div>
            </div>
          </div>
        </div>
        <div class="confirmcancellation">
          <el-button :disabled="isdislob" @click="Onsubmit">确定</el-button>
          <el-button :disabled="isdislob">取消</el-button>
        </div>
      </el-card>
      <!-- 弹框 -->
      <el-dialog
        :title="title == 1 ? '新增' : '编辑'"
        :visible.sync="dialogVisible"
        width="75%"
        :close-on-click-modal="false"
      >
        <el-form ref="form" :model="form" label-width="80px" :rules="rules">
          <el-row>
            <el-col :span="8">
              <el-form-item label="名称" prop="displayName">
                <el-input
                  ref="refinput"
                  v-model="form.displayName"
                  style="width: 80%"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onsbmit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 按钮区域 -->
    <div style="margin-left: 10px; margin-top: 5%">
      <div style="">
        <!-- undate -->
        <!-- <el-row>
          <div class="el-form-item__content">
            <el-upload
              ref="upload"
              accept=".xls,.xlsx"
              action="#"
              :auto-upload="false"
              :multiple="false"
              :file-list="fileList"
              :before-upload="beforeUpload"
              :http-request="uploadHttpRequest"
              :on-remove="fileRemove"
              :on-change="fileChange"
            >
              <el-button size="small" type="primary">选择文件</el-button>
            </el-upload>
          </div>
        </el-row> -->
        <!--  -->
        <!-- <el-button type="primary" @click="exportexc">导出excel</el-button> -->
      </div>
      <div>
        <!-- <el-button type="primary" @click="parseImportData(importData)"
          >parse</el-button
        > -->
      </div>
      <div>
        <el-button type="" @click="add" class="commonbutton">新增</el-button>
      </div>
      <el-button
        type=""
        @click="editpopup"
        style="margin-left: 0; margin-top: 10px"
        class="commonbutton"
        >编辑</el-button
      >
      <!-- <input type="file" accept=".xlsx" @change="onFileChange" /> -->
      <div style="margin-top: 10px">
        <el-button type="" @click="delets" class="commonbutton">删除</el-button>
      </div>
      <div style="margin-top: 10px">
        <el-button type="" @click="topping" class="commonbutton"
          >置顶</el-button
        >
      </div>
      <div style="margin-top: 10px">
        <el-button type="" @click="toppings" class="commonbutton"
          >置底</el-button
        >
      </div>
      <div style="margin-top: 10px">
        <el-button type="" :disabled="isshow" @click="assertion"
        class="commonbutton"
          >排序</el-button
        >
      </div>
      <div style="margin-top: 5px">
        <el-button type="" :disabled="isshow" @click="cancellation"  class="commonbutton"
          >取消</el-button
        >
      </div>
    </div>
    <!-- 选择文件之后的弹框 -->
    <el-dialog title="提示" :visible.sync="filepopupdialogVisible" width="60%">
      <!-- <el-table :data="importData" style="width: 100%"> </el-table> -->
      <div v-for="(item, index) in importData" :key="index">
        <el-checkbox v-model="item.a">备选项</el-checkbox>
        {{ item }}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="filepopupdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="filepopupdialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!--  -->
  </div>
</template>
<script>
import ExcelJS from "exceljs";
import { rowDrop } from "@/components/publicjs/public";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { getporjectlists } from "@/request/commonapi";
import compTable from "@/components/compTable.vue";
import Sortable from "sortablejs";
export default {
  components: { compTable },
  data() {
    return {
      filepopupdialogVisible: false,
      ary1: [],
      ary2: [],
      nums: 0,
      num: 0,
      flitvalues: [], //搜索选择
      filetelists: [], //项目类别
      projectid: [],
      values: "",
      isshow: true,
      rules: {
        itemId: [{ required: true, message: "请选择项目", trigger: "change" }],
        displayName: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        diagnosisId: [
          { required: true, message: "请选择诊断编号", trigger: "change" },
        ],
        isNameIntoSummary: [
          { required: true, message: "请选择小结名称", trigger: "change" },
        ],
        isResultIntoSummary: [
          { required: true, message: "请选择进入小结", trigger: "change" },
        ],
        resultStatusId: [
          { required: true, message: "请选择结果状态", trigger: "change" },
        ],
        simpleCode: [
          { required: true, message: "请输入拼音简码", trigger: "change" },
        ],
      },
      form: {
        displayName: "",
      },
      dialogVisible: false,
      title: 1,
      pages: {
        SkipCount: 0,
        MaxResultCount: 100,
        Sorting: "displayOrder desc",
      },
      itemId: [], //项目
      diagnosisId: [], //诊断
      resultStatusId: [], //结果状态
      isNameIntoSummary: [
        {
          value: "N",
          label: "否",
        },
        {
          value: "Y",
          label: "是",
        },
      ], // 小结名称
      isResultIntoSummary: [
        {
          value: "N",
          label: "否",
        },
        {
          value: "Y",
          label: "是",
        },
      ], //进入小结
      tableData: [],
      initTableData: [],
      tableHeader: [
        // 表头信息，可根据minWidth修改宽度
        { prop: "id", label: "编号", minWidth: "150px" },
        { prop: `creatorName`, label: "创建者" },
        { prop: `creationTime`, label: "创建时间" },
        { prop: `lastModifierName`, label: "修改者" },
        { prop: `lastModificationTime`, label: "创建时间" },
        { prop: "result", label: "结果" },
        // { prop: "simpleCode", label: "拼音简码" },
      ],

      leftdata: [], //左边侧边栏数据
      rightobj: {},
      rightdata: [], //右边侧边栏数据
      isdislob: true,
      flitvalues: [],
      fileList: [],
      importData: [],
    };
  },
  created() {
    this.getlist();
    this.gitprojectcategory();
  },
  mounted() {
    this.rowDrop();
    // this.getdiagnosisitem();
  },
  methods: {
    onFileChange(event) {
      // 获取上传的文件
      const file = event.target.files[0];
      // 调用导入Excel文件的方法
      this.importExcelFile(file);
    },

    importExcelFile(file) {
      this.filepopupdialogVisible = true;
      console.log("333");
      // 创建一个工作簿
      const workbook = new ExcelJS.Workbook();
      // 读取Excel文件
      const reader = new FileReader();
      console.log(reader);
      reader.onload = () => {
        const buffer = reader.result;
        const typedArray = new Uint8Array(buffer);
        const blob = new Blob([typedArray], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });

        // 从Blob中读取Excel文件
        workbook.xlsx.load(blob).then((workbook) => {
          // 获取第一个工作表
          const worksheet = workbook.getWorksheet(1);
          // 处理Excel文件内容
          worksheet.eachRow((row, rowNumber) => {
            this.importData.push(row.values);
            // console.log(`第${rowNumber}行的数据：${rowData}`);
          });
        });
      };
      reader.readAsArrayBuffer(file);
    },

    parseImportData(importData) {
      console.log("importData", importData.length, importData);
      importData.forEach((item) => {
        console.log(item);

        this.importData = item.splice(1).map((items) => {
          return { id: items[0] };
        });
        // this.importData.push(item);

        // item.forEach((item2) => {
        //   item2.displayName = item2[0];
        //   console.log(item2.displayName);

        // });
        console.log(item, "item", item.length);
      });
    },

    // 上传文件之前的钩子：判断上传文件格式、大小等，若返回false则停止上传
    beforeUpload(file) {
      console.log(file);
      console.log("333");
      console.log("2222");
      //文件类型
      const isType = file.type === "application/vnd.ms-excel";
      const isTypeComputer =
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const fileType = isType || isTypeComputer;
      if (!fileType) {
        this.$message.error("上传文件只能是xls/xlsx格式！");
      }

      // 文件大小限制为10M
      const fileLimit = file.size / 1024 / 1024 < 10;
      if (!fileLimit) {
        this.$message.error("上传文件大小不超过10M！");
      }
      return fileType && fileLimit;
    },
    uploadHttpRequest(param) {
      const formData = new FormData(); //FormData对象，添加参数只能通过append('key', value)的形式添加
      formData.append("file", param.file); //添加文件对象
      formData.append("uploadType", this.rulesType);
      const url = `${this.myBaseURL}/operation/ruleImport/importData`; //上传地址
      axios
        .post(url, formData)
        .then((res) => {
          const {
            data: { code, mark },
          } = res;
          if (code === 0) {
            param.onSuccess(); // 上传成功的文件显示绿色的对勾
            this.uploadMark = mark;
          }
          return this.countData(this.uploadMark); //根据响应的 mark 值调用统计结果接口，返回一个promise以便进行链式调用
        })
        .then((res) => {
          //链式调用，统计结果的响应
          const {
            data: { code, data },
          } = res;
          if (code === 0) {
            console.log("统计结果", data);
          }
        })
        .catch((err) => {
          console.log("失败", err);
          param.onError(); //上传失败的文件会从文件列表中删除
        });
    },
    // 统计结果
    countFile(mark) {
      return new Promise((resolve, reject) => {
        axios
          .get(`/operation/ruleImport/countData?mark=${mark}`)
          .then((res) => {
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 点击上传：手动上传到服务器，此时会触发组件的http-request
    submitUpload() {
      this.$refs.upload.submit();
    },
    // 文件发生改变
    fileChange(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]; // 展示最后一次选择的文件
      }
    },
    // 移除选择的文件
    fileRemove(file, fileList) {
      if (fileList.length < 1) {
        this.uploadDisabled = true; //未选择文件则禁用上传按钮
        console.log(file);
      }
    },
    exportexc() {
      // console.log('1');
    },
    // getdiagnosisitem() {
    //   getapi("/api/app/item").then((res) => {

    //     console.log(res);
    //   });
    // },
    Onsubmit() {
      let sampleGroupId = this.form.id;
      console.log(this.form.id);
      console.log(this.rightdata);
      let sdate = [];
      this.rightdata.forEach((element) => {
        let sss = { sampleGroupId: sampleGroupId, asbitemId: element.id };
        sdate.push(sss);
      });
      this.leftdata.forEach((element) => {
        let sss = { sampleGroupId: sampleGroupId, asbitemId: element.id };
        sdate.push(sss);
      });
      console.log(sdate);
      if (sampleGroupId == undefined) {
        this.$message.warning("请选择列表");
      } else {
        postapi("/api/app/item-template-detail/many", sdate).then((res) => {
          this.$message.success("操作成功");
          this.isdislob = true;
        });
      }
    },
    //右侧点击选中
    rightindex(item, index) {
      this.nums = index;
      this.leftobj = item;
      console.log(this.leftobj);
    },
    //q全移去
    allclear() {
      this.isdislob = false;
      if (this.rightdata.length > 0) {
        this.ary1 = this.rightdata;
        this.ary2 = this.leftdata;
        this.updatedate();
        this.rightdata = [];
      }
    },
    //右移动
    removeright() {
      if (this.rightdata.length > 0) {
        this.rightdata.splice(this.num, 1);
        this.leftdata.push(this.leftobj);
        this.isdislob = true;
        this.updatedate();
      }
    },
    //左侧添加按钮
    addobj() {
      if (this.leftdata.length > 0) {
        this.leftdata.splice(this.num, 1);
        this.rightdata.push(this.rightobj);
      }
    },
    //全添加
    addall() {
      this.isdislob = false;
      if (this.leftdata.length > 0) {
        this.ary1 = this.leftdata;
        this.ary2 = this.rightdata;
        this.updatedate();
        this.leftdata = [];
      }
    },
    //左侧双击事件
    shuanji(item, index) {
      console.log(item);
      this.leftdata.splice(index, 1);
      this.rightdata.push(item);
    },

    clickPaixu(item, index) {
      this.rightobj = item;

      // this.ischank = 2;
      this.num = index;
      console.log(this.num);
    },
    //项目类别选择框
    ischangs(v) {
      getapi(`/api/app/item/in-item-type/${v}`).then((res) => {
        console.log(res);
        this.leftdata = res.data;
      });
      console.log(v);
    },
    //获取项目类别
    gitprojectcategory() {
      getapi("/api/app/item-type").then((res) => {
        this.projectid = res.data.items;
      });
    },
    //取消排序
    cancellation() {
      this.$message.info("取消操作");
      this.isshow = true;
      this.getlist();
    },
    //确定排序
    assertion() {
      const result = [];
      this.tableData.forEach((item, index) => {
        // index 从0开始的， 你的displayOrder从大到小排
        console.log(item.id);
        // const currentDisplayOrder = this.tableData.length -1
        const currentDisplayOrder = this.initTableData[index].displayOrder;
        if (item.displayOrder != currentDisplayOrder) {
          // 如果它的displayOrder和它当前所在的位置不同代表挪动过位置
          result.push({ id: item.id, displayOrder: currentDisplayOrder });
        }
      });
      putapi("/api/app/itemtemplate/updatesortmany", {
        itemList: result,
      }).then((res) => {
        this.$message.success("操作成功");
        this.isshow = true;
        this.getlist();
      });
    },
    //初始化
    rowDrop() {
      this.$nextTick(() => {
        const tbody = document.querySelector(".el-table__body-wrapper tbody");
        const _this = this;
        Sortable.create(tbody, {
          handle: ".move",
          animation: 300,

          onEnd({ newIndex, oldIndex }) {
            _this.isshow = false;
            const currRow = _this.tableData.splice(oldIndex, 1)[0];
            _this.tableData.splice(newIndex, 0, currRow);
            _this.tableData.map((item, index) => {
              if (index == newIndex && index == oldIndex) {
                // console.log(item, "新数据");
              } else if (index == oldIndex) {
              } else if (index == newIndex) {
              }
            });
            console.log(_this.tableData.map((item) => item.displayOrder));
          },
        });
      });
    },
    toppings() {
      if (this.form.id == undefined) {
        this.$message.warning("请选择操作的数据");
      } else {
        putapi(
          `/api/app/itemtemplate/updatemanysort?id=${
            this.form.id
          }&SortType=${2}`
        ).then((res) => {
          this.$message.success("操作成功");
          this.getlist();
        });
      }
    },
    topping() {
      if (this.form.id == undefined) {
        this.$message.warning("请选择操作的数据");
      } else {
        putapi(
          `/api/app/itemtemplate/updatemanysort?id=${
            this.form.id
          }&SortType=${1}`
        ).then((res) => {
          this.$message.success("操作成功");
          this.getlist();
        });
      }
    },
    //删除
    delets(row) {
      if (this.form.id == undefined) {
        this.$message.warning("请选择删除的数据");
      } else {
        this.$confirm("是否确认删除,是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            deletapi(`/api/app/item-template/${this.form.id}`).then((res) => {
              this.$message.success("删除成功");
              this.getlist();
            });
          })
          .catch(() => {});
      }
    },
    //编辑弹框
    editpopup() {
      if (this.form.id == undefined) {
        this.$message.warning("请点击选择操作的数据");
      } else {
        this.dialogVisible = true;
        this.title = 2;
        // this.addtoedit();
        getapi(`/api/app/item-template/${this.form.id}`).then((res) => {
          this.form = res.data;
          console.log(res);
        });
      }
    },
    //确定新增或者编辑
    onsbmit() {
      this.$refs.form.validate((v) => {
        if (v) {
          if (this.title == 1) {
            postapi("/api/app/item-template/", this.form).then((res) => {
              this.$message.success("新增成功");
              this.getlist();
              this.dialogVisible = false;
            });
          } else if (this.title == 2) {
            putapi(`/api/app/item-template/${this.form.id}`, this.form).then(
              (res) => {
                this.$message.success("修改成功");
                this.getlist();
                this.dialogVisible = false;
              }
            );
          }
        }
      });
    },
    rowclick(val) {
      getapi(`/api/app/item-template/${val.id}`).then((res) => {
        this.form = res.data;
        console.log(res);
      });
      getapi(`/api/app/item/in-item-type/${val.id}`).then((res) => {
        let dq = res.data;
        if (dq.length > 0) {
          this.rightdata = [];
          dq.forEach((element) => {
            let bb = { displayName: element.displayName, id: element.id };
            this.rightdata.push(bb);
          });
        }
      });
    },
    //ary1 需要追加的数据  ary2目标数组
    updatedate() {
      this.ary1.forEach((item) => {
        let iscz = false;
        this.ary2.forEach((item2) => {
          if (item2.id == item.id) {
            iscz = true;
          }
        });
        if (!iscz) {
          console.log(item.id);
          this.ary2.push(item);
          // this.allid.push({ id: item.id });
        }
      });
    },
    handleRowClick(Row) {
      console.log(Row);
      console.log("1");
    },
    // 新增或者编辑需要的类别
    addtoedit() {
      //项目
      getporjectlists().then((res) => {
        this.itemId = res.data.items;
      });
      // 诊断
      postapi("/api/app/diagnosis/getlistinfilter").then((res) => {
        this.diagnosisId = res.data.items;
      });
      //结果状态
      getapi("/api/app/result-status").then((res) => {
        this.resultStatusId = res.data.items;
      });
      getapi("/api/app/diagnosis/getlistinfilter").then((res) => {});
    },
    //新增弹框
    add() {
      //   this.addtoedit();
      this.dialogVisible = true;
      this.title = 1;
      this.form = {};
      this.$nextTick(() => {
        this.$refs.refinput.focus();
      });
    },
    getlist() {
      getapi("/api/app/item-template/in-filter", this.pages).then((res) => {
        console.log(res);
        this.tableData = res.data.items;
        this.initTableData = [...res.data.items];
      });
      let that = this;
    },
  },
};
</script>
<style scoped>
::v-deep .el-table__header th {
  /* font-size: px; */
  background-color: rgb(245, 245, 245); /* 设置表头背景颜色 */
  color: rgb(113, 113, 113); /* 设置表头文字颜色 */
}
.subjecttitle {
  display: flex;
  justify-content: center;
}
.confirmcancellation {
  margin-left: 45%;
}
.Selectbutton {
  margin-left: 3%;
}
.activetext {
  background: rgb(185, 203, 235);
}
.mainbox {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.mainleftbox {
  width: 200px;
  height: 240px;
  border: 1px solid #ccc;
  margin-left: 6%;
}
.box {
  display: flex;
}
.weixuan {
  text-align: center;
  line-height: 20px;
  background: rgb(185, 203, 235);
}
</style>
