<template>
  <div>
    <!--    编辑-->
    <xy-dialog :is-show.sync="isShow" width="60%" title="学习资料编辑" type="form" :form="detail" :rules="rules"
      @submit="editor" ref="addActivity">

      <template v-slot:activity_list_id>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px">*</span>
            项目 ：
          </div>
          <div class="xy-table-item-content">
            <el-select @change="changeActive" style="width: 300px" v-model="detail.activity_list_id" placeholder="请选择">
              <el-option
                v-for="item in listActivity"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:study_column_id>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px">*</span>
            栏目 ：
          </div>
          <div class="xy-table-item-content">
            <el-cascader
                @change="changeMenu"
                 style="width: 300px"
                v-model="detail.study_column_id"
                :options="menuList"
                :props="{'label':'title','value':'id',checkStrictly: true }"
                clearable></el-cascader>
          </div>
        </div>
      </template>
      <template v-slot:title>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>标题
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写标题" v-model="detail.title" style="width: 300px;" />
          </div>
        </div>
      </template>

      <template v-slot:text>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>内容:
          </div>
          <div class="xy-table-item-content">
            <tinymce ref="tinymce" :height="200" v-model="detail.text" id='tinymce'></tinymce>
          </div>
        </div>
      </template>


      <template v-slot:source>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            来源
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写来源" v-model="detail.source" style="width: 150px;" />
          </div>
        </div>
      </template>

      <template v-slot:reader>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            作者
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写作者" v-model="detail.reader" style="width: 150px;" />
          </div>
        </div>
      </template>

      <template v-slot:duration>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            时长
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写时长" v-model="detail.duration" style="width: 150px;" />
          </div>
        </div>
      </template>



      <template v-slot:poster>
        <div class="xy-table-item">
          <div class="xy-table-item-label">封面图
          </div>
          <div class="xy-table-item-content">

            <div v-if="detail.poster" style="position: relative;">
              <img :src="detail.poster" class="avatar">
              <Button shape="circle" icon="md-close" type="error" size="small" class="img__delete"
                @click="detail.poster = ''"></Button>
            </div>
            <el-upload v-else accept="picture" :limit="1" class="avatar-uploader" list-type="picture-card"
              :action="action" :show-file-list="true" :on-error="uploadFail" :on-success="uploadSuccess"
              :before-upload="uploadBefore">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            尺寸要求：80*80
          </div>

        </div>
      </template>

      <template v-slot:audio_file>
        <div class="xy-table-item">
          <div class="xy-table-item-label">音频文件
          </div>
          <div class="xy-table-item-content">

            <el-upload :file-list="fileList" accept="picture" :limit="1" class="avatar-uploader" :action="action"
              :show-file-list="true" :on-error="uploadFailAuto" :on-success="uploadSuccessAuto"
              :before-upload="uploadBeforeAuto">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </div>

        </div>
      </template>

      <template v-slot:myindex>
        <div class="xy-table-item">
          <div class="xy-table-item-label">排序
          </div>
          <div class="xy-table-item-content">
            <el-input clearable placeholder="请填写排序" v-model="detail.myindex" style="width: 150px;" />
          </div>
        </div>
      </template>

    </xy-dialog>

  </div>
</template>

<script>
  import {
    save,
    show,
    index
  } from "@/api/party/studyResource";
import { index as menulist} from "@/api/index";
  import tinymce from "@/components/Tinymce"
  export default {
    components: {
      tinymce
    },
    props: {
      listActivity: Array
    },
    data() {

      return {
        fileList: [],
        action: `${process.env.VUE_APP_BASE_API}/api/admin/upload-file`,
        listParty: [],
        isShow: false,
        id: "",
        type: "add",
        menuList:[],
        detail: {
          activity_list_id: "",
          study_column_id:'',
          title: "",
          text: "",
          myindex: 1,
          duration: 0,
          source: "",
          reader: "",
          poster: "",
          audio_file: "",
          id: ""
        },
        rules: {
          title: [{
            required: true,
            message: "标题名称必填",
            tigger: "blur"
          }],
          text: [{
            required: true,
            message: "填写内容",
            tigger: "blur"
          }],
          activity_list_id: [{
            required: true,
            message: "选择所属项目"
          }]
        }

      }
    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          if (this.type === 'editor') {
            this.getDetail()
          }
        } else {
          this.id = ''
          this.detail.id = ''
          this.type = ''
          this.$refs['tinymce'].setContent(' ')
          this.$refs['addActivity'].reset()
        }
      }
    },
    methods: {
      // 获取栏目
      changeMenu(e){
        console.log(e,e.at(-1))
        if(e){
          this.detail.study_column_id = e.at(-1)
        }
      },
      changeActive(e){
        if(e){
          this.detail.activity_list_id = e
          this.loadMenu()
        }
      },
      async loadMenu() {
        if(!this.detail.activity_list_id){
          this.$message({
            type:'warning',
            message:'请先选择项目'
          })
          return
        }
        const res = await menulist({
          page: 1,
          page_size: 999,
          with_relations: ['cover'],
          table_name: "study_columns",
          activity_list_id: this.detail.activity_list_id,
          filter: [],
        });

        this.menuList = this.arrayToTree(res.data);
        console.log("list",this.menuList)
      },
      arrayToTree(arr, pid = 0) {
        const result = [];

        arr.forEach(item => {
          if (item.pid === pid) {
            const children = this.arrayToTree(arr, item.id);
            if (children.length) {
              item.children = children;
            }
            result.push(item);
          }
        });

        return result;
      },
      //上传
      uploadFailAuto(err) {
        console.log(err)
      },
      uploadSuccessAuto(response) {
        this.detail.audio_file = response.url
      },
      uploadBeforeAuto(file) {
        if ((file.size / 1000) > 20240) {
          Message({
            type: 'warning',
            message: '上传图片大小超过20M！'
          })
          return false
        }
      },
      //上传
      uploadFail(err) {
        console.log(err)
      },
      uploadSuccess(response) {
        this.detail.poster = response.url
      },
      uploadBefore(file) {
        if ((file.size / 1000) > 2024) {
          Message({
            type: 'warning',
            message: '上传图片大小超过2M！'
          })
          return false
        }
      },
      changeActivity(e) {
        this.load(e);
      },
      load(e) {
        index({
          page_size: 999,
          activity_list_id: e,
          page: 1
        }).then(res => {
          this.listParty = res.data;
        })
      },
      async getDetail() {
        let res = await show({
          id: this.id
        })
        Object.assign(this.detail, res);
        this.loadMenu()
        this.$refs['tinymce'].setContent(res.text ?? ' ')
      },
      editor() {
        console.log("this.detail",this.detail)
        // return
        save(this.detail).then(res => {
          this.isShow = false
          this.$Message.success("操作成功");
          this.$emit('refresh')
        })
      },

    },
    computed: {

    },
    mounted() {
      let that = this;
      let sysInfo = sessionStorage.getItem('sys_info')
      console.log(sysInfo)
      if (sysInfo && sysInfo != "") {
        let _sys = JSON.parse(sysInfo);
        that.detail.activity_list_id = _sys.id;
      }
    }
  }
</script>

<style scoped lang="scss">
  .contract-add-plan {
    min-height: 30px;
    border: 1px solid #dcdee2;
    border-radius: 4px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    align-content: center;

    padding: 0 8px;

    &-no-plan {
      height: 30px;
      line-height: 30px;
      color: #CDD0D5;
    }
  }

  .xy-table-item-label {
    width: 140px;
  }

  .xy-table-item-price {
    position: relative;

    &::after {
      z-index: 1;
      position: absolute;
      right: 0;
      top: 0;
      content: '（元）'
    }

    ::v-deep .el-input__clear {
      position: relative;
      right: 30px;
      z-index: 2;
    }
  }

  .xy-table-item-price-wan {
    position: relative;

    &::after {
      position: absolute;
      right: 0;
      top: 0;
      content: '（万元）'
    }

    ::v-deep .el-input__clear {
      position: relative;
      right: 46px;
      z-index: 2;
    }
  }
</style>
