<!--
 * @Description: 新增/编辑弹框
 * @Author: Sugar.
 * @Date: 2023-11-24 13:55:00
 * @LastEditors: Sugar.
 * @LastEditTime: 22023-11-24 13:55:00
 * @FilePath: \cattle_webui\src\views\venue\performanceHallMr\dialog\seatTemplateEdit.vue
 * @Copyright: Copyright (c) 2016~2023 by Sugar., All Rights Reserved.
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="1200px"
    append-to-body
    :close-on-click-modal="false"
    @close="cancel"
  >
    <div class="dialog">
      <el-row>
        <el-col :span="18" style="padding-right: 15px">
          <div class="title-class">
            <el-row>
              <el-col :span="8" style="padding-right: 15px">
                <el-input placeholder="请输入" v-model.number="seatMapRow">
                  <template slot="append">行</template>
                </el-input>
              </el-col>
              <el-col :span="8" style="padding-left: 15px">
                <el-input placeholder="请输入" v-model.number="seatMapCol">
                  <template slot="append">列</template>
                </el-input>
              </el-col>
              <el-col :span="8" style="padding-left: 15px">
                <el-button @click="setRowCol(seatMapRow, seatMapCol)" style="width: 100%;" type="primary">生成模板</el-button>
              </el-col>
            </el-row>
          </div>
          <div class="box-top-class" style="position:relative;">
            <div class="stage-class">舞台</div>
            <el-button :type="!dragStatus ? 'danger' : 'primary'" size="mini" @click="dragEven" style="position: absolute; bottom: 0; right: 0" icon="el-icon-rank">{{dragStatus ? '开始设置' : '关闭设置'}}</el-button>
          </div>
          <div class="box-class scroll-container-class"
               v-if="seatType"
               @contextmenu.prevent.stop="contextmenuEven"
               @wheel.prevent="wheelHandle"
               ref="scrollContainer"
               style="position: relative; overflow: hidden; padding: 0;"
               >
            <!--  画框确定  -->
            <div class="draw-dialog-class" id="draw-dialog-type" v-show="drawDialogType">
              <div class="box-class" style="border: none; height: 280px" @wheel.stop="wheelDrawHandle">
                <el-form :model="drawForm" ref="drawForm" :rules="drawRules" label-width="100px" label-position="top">
                  <el-form-item label="" prop="status">
                    <el-radio v-model="drawForm.status" label="1">可售</el-radio>
                    <el-radio v-model="drawForm.status" label="2">不可售</el-radio>
                  </el-form-item>
                  <el-form-item label="" prop="seatTypeId" v-if="drawForm.status == 1">
                    <el-select
                      v-model="drawForm.seatTypeId"
                      placeholder="座位类型"
                      clearable
                      style="width: 100%"
                      @change="seatTypeDrawChange"
                    >
                      <el-option
                        v-for="dict in seatList"
                        :key="dict.id"
                        :label="dict.name"
                        :value="dict.id"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="" v-if="drawForm.status == 1">
                    <el-input
                      v-model.number="drawForm.priority"
                      placeholder="座位自动分配优先级"
                      clearable
                      style="width: 100%;"
                    />
                  </el-form-item>
                  <el-form-item >
                    <el-button @click="drawDialogClen">取 消</el-button>
                    <el-button @click="drawDialogOk" style="float: right" type="primary">确 定</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
            <div style="position: relative;">
              <div class="box-bottom-class scroll-container" style="position: absolute; width: 100%; height: 100%" id="drawBox" v-drag :style="{ width: boxWidth ? boxWidth + 'px' : '100%', height: boxWidth ? boxWidth + 'px' : '100%'}" ref="seatBox" v-if="seatType">
                <div v-for="row in seatMap.row" :key="row" style="display: inline-block">
                  <div class="seat-tag"
                       :id="(((row - 1) * seatMap.col) + index + '_')"
                       @click.stop="setSeatTemplateMap((((row - 1) * seatMap.col) + index + '_'))"
                       v-for="(col, index) in seatMap.col"
                       :key="col"
                       :style="{
                       width: seatWidth + 'px',
                       height: seatWidth + 'px',
                       backgroundColor: colSeatMap[((row - 1) * seatMap.col) + index + '_'] && colSeatMap[((row - 1) * seatMap.col) + index + '_'].color ? colSeatMap[((row - 1) * seatMap.col) + index + '_'].color : ''}"
                  >
                    <div v-if="seatWidth > 160" :style="{paddingTop: (seatWidth / 4) + 'px', width: seatWidth + 'px', height: seatWidth + 'px'}" class="seat-p-class">
                      <p style="font-size: 16px !important;"><span>{{colSeatMap[((row - 1) * seatMap.col) + index + '_'].name ? colSeatMap[((row - 1) * seatMap.col) + index + '_'].name : (colSeatMap[((row - 1) * seatMap.col) + index + '_'].rowNo + '排' + (colSeatMap[((row - 1) * seatMap.col) + index + '_'].columnNo) + '座')}}</span><span style="font-size: 14px !important;" v-if="colSeatMap[((row - 1) * seatMap.col) + index + '_'].seatLabel">({{colSeatMap[((row - 1) * seatMap.col) + index + '_'].seatLabel}})</span></p>
                      <p style="font-size: 14px !important;" v-if="colSeatMap[((row - 1) * seatMap.col) + index + '_'].priority">自动分配优先级 <span>({{colSeatMap[((row - 1) * seatMap.col) + index + '_'].priority}})</span></p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div style="margin-top: 5px">
            总座位数：{{ seatMap.row * seatMap.col || 0}}； 可售数量：<span style="color: #67c23a">{{ canNum.length }}</span>； 不可售数量：<span style="color: #f56c6c">{{ unCanNum.length }}</span>
          </div>
        </el-col>
        <el-col :span="6" style="padding-left: 15px">
          <div class="title-class">座位设置</div>
          <div class="box-class" style="height: 540px">
            <el-form :model="form" ref="form" label-width="100px" label-position="top">
              <el-form-item label="是否可售">
                <el-radio v-model="form.status" label="1">可售</el-radio>
                <el-radio v-model="form.status" label="2">不可售</el-radio>
              </el-form-item>
              <el-form-item label="座位类型">
                <el-select
                  v-model="form.seatTypeId"
                  placeholder="座位类型"
                  clearable
                  style="width: 100%"
                  @change="seatTypeChange"
                >
                  <el-option
                    v-for="dict in seatList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="座位自动分配优先级">
                <el-input
                  v-model.number="form.priority"
                  placeholder="优先级"
                  clearable
                  style="width: 100%;"
                />
              </el-form-item>
              <el-form-item label="自定义座位名">
                <el-input
                  v-model="form.name"
                  placeholder="自定义座位名"
                  clearable
                  style="width: 100%;"
                />
              </el-form-item>

              <el-form-item >
                <el-button @click="setSeatMap" style="width: 100%; margin-top: 20px" type="primary">确 定</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button
        type="primary"
        @click="submitForm"
        v-loading.fullscreen.lock="loading"
        element-loading-text="提交中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <span v-if="loading">提交中...</span>
        <span v-else>保存</span>
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { pageList } from '@/api/seatTypeMr/seatTypeMr'
import { seatSaveAndEdit, saveAndEdit, getSelectById } from "@/api/performanceHallMr/performanceHallMr";
import { getToken } from "@/utils/auth";
export default {
  name: "seatTemplateEdit",
  that: this,
  data() {
    return {
      title: "编辑",
      model: "EDIT",
      activeName: '01',
      open: false,
      seatType: false,
      loading: false,
      seatWidth: null,
      seatMap: {
        row: 0,
        col: 0,
      },
      seatMapRow: '',
      seatMapCol: '',
      seatSetMap: {},
      seatTemplateMap: [],
      colSeatMap: {},
      form: {
        id: undefined,
        status: "1",
        content: "",
      },
      seatList: [],
      auditoriumId: '',
      zoom: 10,
      boxWidth: '',
      initWidth: '',
      moveStatus: false,
      mouseMap: {},
      mousemoveMap: {},
      scrollTop: 0,
      scrollLeft: 0,
      scrollEvenTop: 0,
      scrollEvenLeft: 0,
      dragStatus: true,
      canNum: [],
      unCanNum: [],

      drawForm: {
        status: '1'
      },
      drawDialogType: false,
      drawRules: {
        status: [{ required: true, message: "请选择状态", trigger: ["change","blur"] }],
        seatTypeId: [{ required: true, message: "请选择座位类型", trigger: ["change","blur"] }]
      },
    };
  },
  methods: {
    drawDialogClen() {
      let drawDialog = document.getElementById("draw-dialog-type");
      drawDialog.style.display = "none";
      let drawDiv = document.getElementById("drawDiv");
      drawDiv.remove();

      this.$forceUpdate();
    },
    // 画框座位设置
    drawDialogOk() {
      this.$refs["drawForm"].validate(async (valid) => {
        if (valid) {
          let drawDialog = document.getElementById("drawDiv");
          // 获取div元素的坐标点
          let rect = drawDialog.getBoundingClientRect();
          let P_div = document.getElementById("drawBox");

          let P_div_list = P_div.children; // 获取行子集
          let select_div = [];
          // 循环判断是否在选择框里
          for (let i = 0; i < P_div_list.length; i++) {
            if(P_div_list[i] && P_div_list[i].childNodes) {
              let child_div = P_div_list[i].children
              for (let j = 0; j <child_div.length; j++) {
                let rect_div = child_div[j].getBoundingClientRect();
                if(rect.top < (rect_div.top + rect_div.height) && rect.bottom > (rect_div.bottom - rect_div.height) &&
                  rect.left < (rect_div.left + rect_div.width) && rect.right > (rect_div.right - rect_div.width)) {
                  select_div.push(child_div[j].getAttribute("id"));
                }
              }
            }
          }
          for (let i = 0; i < select_div.length; i++) {
            this.setSeatDrawMap(select_div[i]);
          }
          this.drawDialogClen()
        }
      });
    },
    // 画框座位放置参数
    setSeatDrawMap(key) {
      let map = this.colSeatMap[key];
      map.status = this.drawForm.status;
      map.color = this.drawForm.seat ? this.drawForm.seat.color : '';
      map.seatTypeId = this.drawForm.seat ? this.drawForm.seat.id : '';
      map.seatLabel = this.drawForm.seat ? this.drawForm.seat.name : '';
      map.name = "";
      map.priority = this.drawForm.priority;

      if(this.drawForm.status == 2) {
        map.color = '#7d7d7e';
        map.seatTypeId = '';
        map.seatLabel = '';
      }
      this.$set(this.colSeatMap, key, map);
      this.countNum();
      this.$forceUpdate()
    },
    // 鼠标滚动
    wheelHandle(e) {
      if(e.wheelDelta > 0){
        this.seatWidth = Math.trunc(this.seatWidth + 10);
      } else {
        if(this.initWidth > this.seatWidth + 5){
          // this.seatWidth = this.initWidth;
        } else {
          this.seatWidth = Math.trunc(this.seatWidth -10)
        }
      }
      this.boxWidth = this.seatWidth * this.seatMap.col + 100;
      // this.seatWidth = (this.seatWidth + this.zoom);
      this.$forceUpdate();
    },
    wheelDrawHandle(e) {
      if(e.preventDefault){
        e.preventDefault()
      } else {
        e.returnValue = false
      }
      return false
    },
    contextmenuEven(e) {
      return false;
    },
    dragEven(){
      this.dragStatus = !this.dragStatus;
    },
    /**
     * 打开弹框
     * @date 2023-11-22
     * @param {any} obj
     * @returns {any}
     */
    openDialog(title, obj) {
      this.open = true;
      this.seatType = false;
      this.getSeatTypeList();
      this.colSeatMap = {}
      this.drawForm = {};
      this.$set(this.drawForm, 'status', '1')
      this.boxWidth = 0;
      this.dragStatus = true;
      this.$set(this.form, 'status', '1')
      if (obj){
        this.title = "座位模板";
        this.auditoriumId = obj.id;
        this.$set(this.seatMap, 'row', obj.rows);
        this.$set(this.seatMap, 'col', obj.cols);
        this.$set(this, 'seatMapRow', obj.rows);
        this.$set(this, 'seatMapCol', obj.cols);

        this.getSelectByIdApi(obj)
      }else{
        this.seatType = true;
        this.title = "座位模板";
        this.$nextTick(() => {
          this.$refs["form"].clearValidate();
        });
      }
    },
    /** 获取详情 */
    getSelectByIdApi(row) {
      const id = row.id
      getSelectById(id).then(response => {
        const dataList = response.data;
        this.$nextTick(() =>{
          dataList.forEach(item => {
            if(item.status == 2){
              item.color = '#7d7d7e';
            }
            this.$set(this.colSeatMap, item.sortId + '_', item);
          })
          this.seatType = true;
          this.$nextTick(() =>{
            this.boxWidth = this.$refs.seatBox.offsetWidth;
            this.seatWidth = ((this.$refs.seatBox.offsetWidth - 10 - (this.seatMap.col * 2))/this.seatMap.col);
            this.initWidth = Math.trunc((this.$refs.seatBox.offsetWidth - 10 - (this.seatMap.col * 2))/this.seatMap.col);
          })
          this.countNum();
        })
      });
    },
    /** 设置座位模板行列 */
    setRowCol(row, col) {
      if(!row || !col){
        this.$message.error("请输入行和列!");
        return false;
      }
      if(row <= 0 || col <= 0){
        this.$message.error("请输入大于0的行和列!");
        return false;
      }
      if(this.colSeatMap) {
        this.$confirm('此操作将重置座位模板, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.seatMap.row = row;
          this.seatMap.col = col;
          this.seatType = false;
          this.seatType = true;
          this.colSeatMap  = {}
          let index = 0;
          for (let i = 1; i < this.seatMap.row + 1; i++) {
            for (let j = this.seatMap.col; j > 0; j--) {
              let rowColMap = {
                "auditoriumId": this.auditoriumId,
                "name": "",
                "rowNo": i,
                "sortId": index,
                "columnNo": j,
                "seatTypeColor": '#fdfdfd',
                "seatTypeId": "",
                "seatLabel": "",
                "priority": "",
                "status": 2
              };
              this.$set(this.colSeatMap, index + '_', rowColMap);
              index ++;
            }
          }
          this.$nextTick(() =>{
            this.boxWidth = this.$refs.seatBox.offsetWidth;
            this.seatWidth = ((this.$refs.seatBox.offsetWidth - 10 - (this.seatMap.col * 2))/this.seatMap.col);
            this.initWidth = Math.trunc((this.$refs.seatBox.offsetWidth - 10 - (this.seatMap.col * 2))/this.seatMap.col);
          })
          this.countNum();
        }).catch(() => {

        });
      }
    },
    /** 座位类型列表 */
    getSeatTypeList() {
      pageList(this.addDateRange({pageNum: 1, pageSize: 100}))
        .then(response => {
            this.seatList = response.data.rows;
          }
        );
    },
    /** 座位类型选择事件 */
    seatTypeChange(val) {
      this.$set(this.form, 'priority', '');
      this.$set(this.form, 'name', '');
      this.seatList.forEach(item => {
        if(val == item.id){
          this.form.seat = item
        }
      })
    },
    /** 画框座位类型选择事件 */
    seatTypeDrawChange(val) {
      this.$set(this.drawForm, 'priority', '');
      this.seatList.forEach(item => {
        if(val == item.id){
          this.drawForm.seat = item
        }
      })
    },
    /** 座位设置确认事件 */
    setSeatMap() {
      this.seatSetMap = {};
      this.seatSetMap.status = this.form.status;
      this.seatSetMap.color = this.form.seat.color;
      this.seatSetMap.seatTypeId = this.form.seat.id;
      this.seatSetMap.seatLabel = this.form.seat.name;
      this.seatSetMap.name = this.form.name;
      this.seatSetMap.priority = this.form.priority;

      if(this.seatSetMap.status == 2) {
        this.seatSetMap.color = '#7d7d7e';
        this.seatSetMap.seatTypeId = '';
        this.seatSetMap.seatLabel = '';
      }
    },

    // 计算可售和不可售数量
    countNum() {
      this.canNum = [];
      this.unCanNum = [];
      if(this.colSeatMap) {
        for (const key in this.colSeatMap) {
          if(this.colSeatMap[key].status == 2 || !this.colSeatMap[key].status){
            this.unCanNum.push(key)
          } else if (this.colSeatMap[key].status == 1) {
            this.canNum.push(key)
          }
        }
      }
    },

    // 点击座位放置参数
    setSeatTemplateMap(key) {
      if(this.dragStatus){
        return false
      }
      if(!this.seatSetMap.status){
        this.seatSetMap.color = '#7d7d7e';
      }
      let map = this.colSeatMap[key];
      map.status = this.seatSetMap.status;
      map.color = this.seatSetMap.color;
      map.seatTypeId = this.seatSetMap.seatTypeId;
      map.seatLabel = this.seatSetMap.seatLabel;
      map.name = this.seatSetMap.name;
      map.priority = this.seatSetMap.priority;
      this.$set(this.colSeatMap, key, map);
      this.countNum();
      this.$forceUpdate()
    },
    /**
     * 保存
     * @date 2023-11-22
     * @returns {any}
     */
    submitForm() {
      let that = this;
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          let postList = []
          for (const codeKey in this.colSeatMap) {
            postList.push(this.colSeatMap[codeKey])
          }
          try {
            this.loading = true;
            const { code } = await saveAndEdit({ id: this.auditoriumId, rows: this.seatMap.row, cols: this.seatMap.col });
            if (code === 200) {
              let postList = []
              for (const codeKey in this.colSeatMap) {
                postList.push(this.colSeatMap[codeKey])
              }
              const { code } = await seatSaveAndEdit(postList);
              if (code === 200) {
                that.$message.success("操作成功!");
                that.$emit("getList");
                that.cancel();
              }
            }
          } catch (error) {
          } finally {
            this.loading = false;
          }
        }
      });
    },
    /**
     * 重置
     * @date 2023-11-22
     * @returns {any}
     */
    reset() {
      this.$refs["form"].resetFields();
      this.form.id = undefined;
    },
    /**
     * 关闭弹框
     * @date 2023-11-22
     * @returns {any}
     */
    cancel() {
      this.reset();
      this.open = false;
    },
    /**
     * 上传成功
     * @date 2023-11-22
     * @param {any} res
     * @returns {any}
     */
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        // this.form.mainImg = res?.data?.url;
        this.$set(this.form, 'mainImg', res?.data?.url)
      }
    },
    /**
     * 上传文件之前之前
     * @date 2023-11-22
     * @param {any} file
     * @returns {any}
     */
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      if (!isJPG) {
        this.$message.error("上传头像图片只能是jpg或png格式!");
      }
      return isJPG;
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog {
  padding: 0 30px;
  max-height: 75vh;
  overflow-y: auto;
}
.draw-dialog-class{
  border-radius: 10px;
  height: 240px;
  width: 220px;
  background-color: #fff;
  position: absolute;
  z-index: 55;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.dialog {
  padding: 0 30px;

  .title-class{
    text-align: center;
    color: #6e6e6e;
    margin: 10px auto;
  }
  .box-top-class{
    .stage-class{
      margin: 10px auto;
      width: 160px;
      height: 80px;
      border: 2px solid #7d7d7e;
      text-align: center;
      line-height: 80px;
    }
  }
  .box-class ::-webkit-scrollbar{ /*滚动条基本样式，高度*/
    width:10px;height:10px;
  }
  .box-class{
    width: 100%;
    height: 500px;
    border: 2px solid #7d7d7e;
    border-radius: 4px;
    padding: 10px;

    .box-bottom-class{
      //border: 2px solid #5656c2;
      //margin-top: 15px;
      //padding-left: 4px;

      .seat-tag{
        display: inline-block;
        border: 1px solid #7d7d7e;
        margin-right: 2px;
        cursor: pointer;
        background: url("../../../../assets/images/seat-icon.png") no-repeat;
        background-size: 100% 100%;
        position: relative;

        &:hover{
          opacity: 0.8;
        }
      }
      .seat-p-class{
        position: absolute;
        left: 0;
        top: 0;
        text-align: center;
        font-size: 18px;
        display: inline-block;
        color: white;
      }
    }
  }

  .upload-btn {
    width: 100px;
    height: 100px;
    background-color: #fbfdff;
    border: dashed 1px #c0ccda;
    border-radius: 5px;
    i {
      font-size: 30px;
      margin-top: 20px;
    }
    &-text {
      margin-top: -10px;
    }
  }
  .avatar {
    cursor: pointer;
  }
}
</style>
