<!--
 * @Description: 新增/编辑弹框
 * @Author: Sugar.
 * @Date: 2023-11-24 13:55:00
 * @LastEditors: Sugar.
 * @LastEditTime: 2023-11-24 13:55:00
 * @FilePath: \cattle_webui\src\views\programmeMr\dialog\AddOrEditDialog.vue
 * @Copyright: Copyright (c) 2016~2023 by Sugar., All Rights Reserved.
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="700px"
    append-to-body
    :close-on-click-modal="false"
    @close="cancel"
  >
    <div class="dialog">
      <el-form :model="form" ref="form" :rules="rules" label-width="80px">
        <el-tabs v-model="activeName">
          <!--    基础信息     -->
          <el-tab-pane label="基础信息" name="01">
            <el-form-item label="剧目名称" prop="name" style="margin-top: 20px">
              <el-input
                v-model="form.name"
                placeholder="剧目名称"
                clearable
              />
            </el-form-item>
            <el-form-item label="主办方" prop="sponsorId">
              <el-select
                v-model="form.sponsorId"
                placeholder="主办方"
                clearable
                style="width: 100%"
                @change="changePerform"
              >
                <el-option
                  v-for="dict in performList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="票务选择" prop="goodsIdList">
              <el-select
                v-model="form.goodsIdList"
                placeholder="票务选择"
                clearable
                multiple
                style="width: 100%"
                @change="changePerform"
              >
                <el-option
                  v-for="dict in ticketList"
                  :key="dict.id"
                  :label="dict.goodsName"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否启用" prop="status">
              <el-select
                v-model="form.status"
                placeholder="状态"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in statusList"
                  :key="dict.value"
                  :label="dict.name"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-tab-pane>

          <!--    演出信息     -->
          <el-tab-pane label="演出信息" name="02">
            <el-form-item label="上映日期" style="margin-top: 20px">
              <el-date-picker
                v-model="form.releaseDate"
                type="date"
                value-format="yyyy-MM-dd"
                style="width: 240px;"
                placeholder="选择上映日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="演出时长">
              <el-input
                placeholder="演出时长"
                type="number"
                v-model="form.showDuration"
                @change="changePriceAmount('showDuration')"
                clearable
                style="width: 240px;margin-right: 10px"
              />
              <span>分钟</span>
            </el-form-item>
            <el-form-item label="演出人数">
              <el-input
                type="number"
                v-model="form.peopleNum"
                placeholder="演出人数"
                @change="changePriceAmount('peopleNum')"
                clearable
                style="width: 240px;margin-right: 10px"
              />
              <span>人</span>
            </el-form-item>
            <el-form-item label="演员信息">
              <el-button type="text" @click="performerOpen">添加</el-button>
            </el-form-item>
            <el-form-item label="剧目海报">
              <el-upload
                ref="upload"
                class="avatar-uploader"
                :action="uploadObj.url"
                :headers="uploadObj.headers"
                :show-file-list="false"
                accept=".jpg,.png"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <div class="avatar" v-if="form.showImg">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="form.showImg"
                    fit="cover"
                  />
                </div>
                <div class="upload-btn" v-else>
                  <i class="el-icon-plus"></i>
                  <div class="upload-btn-text">上传照片</div>
                </div>
                <div class="el-upload__tip" slot="tip">只能上传.jpg或.png格式</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="宣传图">
              <el-upload
                ref="upload"
                :action="uploadObj.url"
                :headers="uploadObj.headers"
                accept=".jpg,.png"
                :on-success="handlePhotoListSuccess"
                :before-upload="beforeAvatarUpload"
                list-type="picture-card"
                :file-list="form.photoList"
                :on-remove="handleRemove"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="剧情介绍">
              <editor v-model="form.performSnapshot" :fileSize="20" :min-height="200" />
            </el-form-item>
          </el-tab-pane>

          <!--    观影须知     -->
          <el-tab-pane label="观影须知" name="03">
            <el-form-item label="观影须知" style="margin-top: 20px">
              <editor v-model="form.performNotice" :fileSize="20" :min-height="200" />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </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
      title="添加演员信息"
      :visible.sync="performerVisible"
      width="800px"
      append-to-body
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <div>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
        </el-row>
        <el-table ref="tables"  :data="performerList" border>
          <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
          <el-table-column label="姓名" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.performerName"
                placeholder="姓名"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column label="图片" align="center">
            <template slot-scope="scope">
              <el-upload
                ref="upload"
                class="avatar-uploader"
                :action="uploadObj.url"
                :headers="uploadObj.headers"
                :show-file-list="false"
                accept=".jpg,.png"
                :on-success="handlePerformerAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <div class="avatar" v-if="scope.row.performerHead" @click="changeIndexEven(scope)">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="scope.row.performerHead"
                    fit="cover"
                  />
                </div>
                <div class="upload-btn" v-else  @click="changeIndexEven(scope)">
                  <i class="el-icon-plus"></i>
                  <div class="upload-btn-text">上传照片</div>
                </div>
                <div class="el-upload__tip" slot="tip">只能上传.jpg或.png格式</div>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column label="角色名" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.performerRole"
                placeholder="角色名"
                clearable
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleDelete(scope.row,scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="performerVisible = false">取 消</el-button>
        <el-button type="primary" @click="performerEven">确 定</el-button>
      </div>
    </el-dialog>

  </el-dialog>
</template>

<script>
// import { updateNoticeMgr } from "@/api/system/noticeMgr";
import { saveAndEdit, getSelectById } from '@/api/programmeMr/programmeMr'
import { ticketPageList } from '@/api/ticketMr/ticketMr'
import Editor from "@/components/Editor";
import { getToken } from "@/utils/auth";
import { pageList } from '@/api/performMr/performMr'
export default {
  name: "addAndEdit",
  components: {
    Editor,
  },
  data() {
    return {
      title: "编辑",
      model: "EDIT",
      activeName: '01',
      // 演员信息弹窗
      performerVisible: false,
      // 演员信息
      performerList: [],
      // 演员上传图片索引
      performerIndex: 0,
      open: false,
      loading: false,
      form: {
        id: undefined,
        type: "",
        content: "",
      },
      rules: {
        name: [{ required: true, message: "请输入剧目名称", trigger: "blur" }],
        sponsorId: [{ required: true, message: "请选择主办方", trigger: "blur" }],
        goodsIdList: [{ required: true, message: "请选择票务信息", trigger: "blur" }],
        status: [{ required: true, message: "请选择是否启用状态", trigger: "blur" }]
      },
      uploadObj: {
        url: process.env.VUE_APP_UPLOAD_FILE_API + "/upload/single/minio",
        Headers: { Authorization: "Bearer " + getToken() },
      },
      statusList: [
        {id: 1, name: '是', value: 1},
        {id: 2, name: '否', value: 2},
      ],
      performList: [],
      ticketList: []
    };
  },
  created() {
    this.getList();
    this.ticketPageListApi();
  },
  methods: {
    /** 查询主办方列表 */
    getList() {
      pageList({pageNum: 1, pageSize: 100})
        .then(response => {
            this.performList = response.data.rows;
          }
        );
    },
    /** 查询票务列表 */
    ticketPageListApi() {
      ticketPageList({pageNum: 1, pageSize: 100, goodsType: 2, classifyId: 1, status: 0})
        .then(response => {
            this.ticketList = response.data.rows;
          }
        );
    },
    /** 主办方选择事件 */
    changePerform(val) {
      this.performList.forEach(item => {
        if(item.id == val){
          this.form.sponsorName = item.name
        }
      })
    },
    /** 价格输入事件 */
    changePriceAmount(key) {
      if(this.form[key] * 1 < 0){
        this.$message.error("输入需大于或等于0!");
        this.$set(this.form, key, '');
        return false
      }
    },
    /**
     * 打开弹框
     * @date 2023-11-22
     * @param {any} obj
     * @returns {any}
     */
    openDialog(title, obj) {
      this.open = true;
      this.form = {};
      this.activeName = '01';
      if (obj){
        this.title = "编辑剧目管理";
        this.getSelectByIdApi(obj)
      }else{
        this.title = "添加剧目管理";
        this.$nextTick(() => {
          this.$refs["form"].clearValidate();
        });
      }
    },
    /** 获取详情 */
    getSelectByIdApi(row) {
      const id = row.id
      getSelectById(id).then(response => {
        const obj = response.data;
        this.$nextTick(() => {
          this.$set(this.form, 'id', obj.id);
          // 基础信息
          this.$set(this.form, 'name', obj.name);
          this.$set(this.form, 'sponsorId', obj.sponsorId);
          this.$set(this.form, 'sponsorName', obj.sponsorName);
          let goodsIdList = []
          obj.goodsList.forEach(item => {
            goodsIdList.push(item.goodsId);
          })
          this.$set(this.form, 'goodsIdList', goodsIdList);
          this.$set(this.form, 'status', obj.status);

          // 演出信息
          this.$set(this.form, 'releaseDate', obj.releaseDate);
          this.$set(this.form, 'showDuration', obj.showDuration);
          this.$set(this.form, 'peopleNum', obj.peopleNum);
          this.$set(this.form, 'showImg', obj.showImg);
          this.$set(this.form, 'performSnapshot', obj.performSnapshot);
          this.performerList = obj.performerList || [];
          obj.photoList.forEach(item => {
            item.url = item.imageUrl
          })
          this.$set(this.form, 'photoList', obj.photoList);

          // 观影须知
          this.$set(this.form, 'performNotice', obj.performNotice);
        });
      });
    },
    /**
     * 保存
     * @date 2023-11-22
     * @returns {any}
     */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          if(this.form.photoList && this.form.photoList.length < 3) {
            this.$message.error("上传的宣传图不能少于三张!");
            return false
          }
          try {
            this.loading = true;
            const { code } = await saveAndEdit({ ...this.form });
            if (code === 200) {
              this.$message.success("操作成功!");
              this.$emit("getList");
              this.cancel();
            }
          } catch (error) {
          } finally {
            this.loading = false;
          }
        }
      });
    },
    /**
     * 演员信息添加
     * @date 2023-11-22
     * @returns {any}
     */
    performerEven() {
      let target=[...this.performerList];
      this.form.performerList = JSON.parse(JSON.stringify(target));
      this.performerVisible = 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, 'showImg', res?.data?.url)
      }
      console.log(this.form.photoList)
    },
    /**
     * 剧目海报上传成功
     * @date 2023-11-22
     * @param {any} res
     * @returns {any}
     */
    handlePhotoListSuccess(res) {
      if (res.code === 200) {
        let photo = {
          imageUrl: res?.data?.url,
          url: res?.data?.url,
          photoType: '2'
        }
        if(!this.form.photoList){
          this.form.photoList = []
        }
        // this.form.photoList.push(photo);
        this.$set(this.form.photoList, this.form.photoList.length, photo);
      }
    },
    handleRemove(file, fileList) {
      // this.form.photoList = []
      // fileList.forEach(item => {
      //   if(item.response && item.response.data){
      //     let res = item.response.data;
      //     let photo = {
      //       imageUrl: res?.data?.url,
      //       url: res?.data?.url,
      //       photoType: '2'
      //     }
      //     if(!this.form.photoList){
      //       this.form.photoList = []
      //     }
      //     // this.form.photoList.push(photo);
      //     this.$set(this.form.photoList, this.form.photoList.length, photo);
      //   }
      // })
      this.form.photoList.forEach((item, index) => {
        if(item.uid == file.uid){
          this.form.photoList.splice(index, 1)
        }
      })
    },
    /**
     * 上传文件之前之前
     * @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;
    },
    /**
     * 演员新增
     * @date 2023-11-22
     */
    handleAdd() {
      if(!this.performerList){
        this.performerList = []
      }
      this.performerList.push({})
    },
    /**
     * 演员删除
     * @date 2023-11-22
     */
    handleDelete(row, index) {
      this.$confirm('是否确认删当前数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.performerList.splice(index, 1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    /**
     * 演员弹窗打开
     * @date 2023-11-22
     */
    performerOpen() {
      if(!this.form.performerList){
        this.form.performerList = []
      }
      let target=[...this.form.performerList];
      this.performerList = JSON.parse(JSON.stringify(target));
      this.performerVisible = true;
    },
    /**
     * 演员图片上传成功
     * @date 2023-11-22
     * @param {any} res
     * @returns {any}
     */
    handlePerformerAvatarSuccess(res) {
      if (res.code === 200) {
        // this.form.mainImg = res?.data?.url;
        this.$set(this.performerList[this.performerIndex], 'performerHead', res?.data?.url);
      }
    },
    /**
     * 演员图片上传点击记录当前索引
     * @date 2023-11-22
     * @param {any} row
     * @returns {any}
     */
    changeIndexEven(row) {
      this.performerIndex = row.$index;
    }
  },
};
</script>

<style lang="scss" scoped>
.dialog {
  padding: 0 30px;
  max-height: 65vh;
  overflow-y: auto;
}
.dialog {
  padding: 0 30px;
  .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;
  }
}
.el-table{
  .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>
