<template>
  <div class="_tablepage">
    <searchForm
      :searchForm="pageData.searchForm"
      :searchData="pageData.queryData"
      :searchHandle="pageData.searchHandle"
    >
    </searchForm>
    <cusTable
      :loading="loading"
      :isSelection="true"
      :isIndex="true"
      :isPagination="true"
      :isHandle="true"
      :tableCols="pageData.tableCols"
      :tableHandles="pageData.tableHandles"
      :tableData="pageData.tableData"
      :tablePage="pageData.tablePage"
      @handleCurrentChange="searchTableList"
      @selectChange="selectChange"
      @handleSizeChange="searchTableList"
    ></cusTable> 
    <modal
      ref="modalRef"
      :modalConfig="pageData.modalConfig"
      :modalForm="pageData.modalForm"
      :modalData="pageData.modalData"
      :modalHandles="pageData.modalHandles"
      @closeModal="closeModal()"
    ></modal>
  </div>
</template>
<script>
import modal from "../../../components/common/modal/modal.vue";
import searchForm from "../../../components/common/searchform/searchForm.vue";
import cusTable from "../../../components/common/table/custable.vue";
export default {
  components: { searchForm, cusTable, modal },
  data() {
    return {
      //加载动画
      loading:false,
      typeList: [],
      pageData: {
        //查询表单内容 start
        searchForm: [
          { type: "Input", label: "关键字", prop: "searchName",placeholder:'标题、来源、编辑者名称',width:'230px' },
          {
            type: "Select",
            label: "内容类型",
            prop: "isVideo",
            options: [{
              label:'资讯',value:0
            },{label:'视频',value:1}],
          },
          {
            type: "DateTimeRange",
            label: "发布时间范围",
            prop: "time",
          },
        ],
        //查询表单内容 end
        //查询条件 start
        queryData: {
          searchName: "",
          contentTypeId: "",
          time: [],
          isVideo:0
        },
        //查询条件 end
        //查询表单按钮start
        searchHandle: [
          {
            label: "查询",
            type: "primary",
            handle: () => this.searchTableList(),
            auth: "reportDatasource_search",
          },
          {
            label: "重置",
            type: "warning",
            handle: () => this.resetSearch(),
            auth: "reportDatasource_search",
          },
        ],
        //查询表单按钮end
        //表格数据start
        tableData: [],
        //表格数据end
        //表格工具栏按钮 start
        tableHandles: [
          {
            label: "新增",
            type: "primary",
            handle: () => this.showModal(this.commonConstants.modalType.insert),
            auth: "reportDatasource_insert",
          },
          {
            label: "批量删除",
            type: "danger",
            handle: () => this.deleteBatch(),
            auth: "reportDatasource_batchDelete",
          },
        ],
        //表格工具栏按钮 end
        selectList: [], //表格选中的数据
        //表格分页信息start
        tablePage: {
          currentPage: 1,
          pageSize: 5,
          pageTotal: 0,
          pageSizeRange: [5, 10, 20, 50],
        },
        //表格分页信息end
        //表格列表头start
        tableCols: [
          { label: "标题", prop: "title", align: "center" },
          { label: "副标题", prop: "subtitle", align: "center" },
          { label: "资讯来源", prop: "source", align: "center" },
          { label: "编辑者", prop: "editorName", align: "center" },
          { label: "作者", prop: "author", align: "center" },
          { label: "封面", type: "image", prop: "imageUrl", align: "center" },
          { label: "外链", prop: "contentLink", align: "center" },
          { label: "阅读数", prop: "readNumber", align: "center" },
          { label: "喜欢", prop: "likeNumber", align: "center" },
          { label: "收藏数", prop: "collectNumber", align: "center" },
          {
            label: "操作",
            prop: "operation",
            align: "center",
            type: "button",
            width:'180px',
            fixed: "right",
            btnList: [
              {
                label: "预览",
                type: "text",
                auth: "reportDatasource_getDetail",
                handle: (row) =>
                  this.showModal(this.commonConstants.modalType.detail, row),
              },
              {
                label: "编辑",
                type: "text",
                auth: "reportDatasource_update",
                handle: (row) =>
                  this.showModal(this.commonConstants.modalType.update, row),
              },
              {
                label: "删除",
                type: "text",
                auth: "reportDatasource_delete",
                handle: (row) => this.deleteOne(row.contentInfoId),
              },
            ],
          },
        ],
        //表格列表头end
        //modal配置 start
        modalConfig: {
          title: "新增", //弹窗标题,值为:新增，查看，编辑
          show: false, //弹框显示
          formEditDisabled: false, //编辑弹窗是否可编辑
          width: "80vw", //弹出框宽度
          modalRef: "modalRef", //modal标识
          type: "1", //类型 1新增 2编辑 3保存
        },
        //modal配置 end
        //modal表单 start
        modalForm: [
          {
            type: "Input",
            label: "标题",
            prop: "title",
            rules: { required: true, maxLength: 100 },
            width: "900px",
          },
          {
            type: "Input",
            label: "副标题",
            prop: "subtitle",
            rules: { maxLength: 100 },
            width: "900px",
          },
          {
            type: "Input",
            label: "资讯来源",
            prop: "source",
            rules: { required: true, maxLength: 100 },
            width: "300px",
          },
          {
            type: "Input",
            label: "作者",
            prop: "author",
            rules: { maxLength: 100 },
            width: "300px",
          },
          {
            type: "Input",
            label: "编辑者",
            prop: "editorName",
            rules: { maxLength: 100 },
            width: "300px",
          },
          {
            type: "Input",
            label: "外链",
            prop: "contentLink",
            rules: { maxLength: 100 },
            width: "300px",
          },
          {
            type: "Input",
            label: "关键词",
            prop: "keywords",
            rules: { maxLength: 100 },
            width: "300px",
          },
          { 
            type:'Radio',
            prop:'isVideo',
            label:'内容类型',
            radios:[{label:'资讯',value:'0'},{label:'视频',value:'1'}],
            width: "300px",
          },
          {
            type: "Upload",
            label: "封面",
            fileUrl: "imageUrl",
            prop: "fileList",
            accept: ".jpg,.jpeg,.png,.JPG,.JPEG",
            width: "300px",
          },
          {
            type: "Tinymce",
            label: "资讯内容",
            prop: "content",
            rules: { required: true },
            width: "1200px",
          },
        ],
        newModalForm:[
          {
            type: "Upload",
            label: "封面",
            fileUrl: "imageUrl",
            prop: "fileList",
            accept: ".jpg,.jpeg,.png,.JPG,.JPEG",
            width: "300px",
          },
          ],//咨询专属内容
        videoModalForm:[
          {
            type: "Upload",
            label: "封面",
            fileUrl: "imageUrl",
            prop: "fileList",
            accept: ".jpg,.jpeg,.png,.JPG,.JPEG",
            width: "300px",
          },
          {
            type: "Upload",
            label: "视频",
            fileUrl: "videoUrl",
            prop: "fileListVideo",
            listType:'text',
            width: "300px",
            isVideo:true,
            rules:{required:true},
            accept:'.mp4,.avi,.mov,.rmvb,.flv,.MP4,.AVI,.MOV,.RMVB,.FLV',
            tips:'请上传视频文件'
          },
        ],//视频专属内容
        //modal表单 end
        //modal 数据 start
        modalData: {
          userId: "",
          content: "",
          fileUrl: "",
          fileList: [],
          isVideo:'0',
          videoUrl:'',
          source:'',
          fileListVideo:[]
        },
        //modal 数据 end
        //modal 按钮 start
        modalHandles: [
          { label: "取消", type: "default", handle: () => this.closeModal() },
          { label: "提交", type: "primary", handle: () => this.save() },
        ],
        //modal 按钮 end
      },
    };
  },
  watch:{
    "pageData.modalData.isVideo":{
      handler:function(val,oldval){
        // console.log(val)
        if(val==='1'&&oldval==='0'){
          this.pageData.modalForm.splice(-1-this.pageData.newModalForm.length,this.pageData.newModalForm.length,...this.pageData.videoModalForm)
          
       }
       else if(val==='0'&&oldval==='1'){
         this.pageData.modalForm.splice(-1-this.pageData.videoModalForm.length,this.pageData.videoModalForm.length,...this.pageData.newModalForm)
       }
      }
    },
    "pageData.modalData.fileList":{
      handler:function(val){
        if(val&&val.length===0){
          this.pageData.modalData.imageUrl=''
        }
      }
    },
    "pageData.modalData.fileListVideo":{
      handler:function(val){
        if(val&&val.length===0){
          this.pageData.modalData.videoUrl=''
        }
      }
    }
  },
  activated() {
    this.searchTableList();
  },
  methods: {
    /**
     * @description: 获取表格数据
     * @param {type}
     * @return:
     * @author: ym
     */
    searchTableList() {
      this.loading=true;
      // 初始化obj
      var obj = {};
      Object.assign(obj, this.pageData.queryData, this.pageData.tablePage);
      obj.page = this.pageData.tablePage.currentPage;
      obj.limit = this.pageData.tablePage.pageSize;
      delete obj["pageSizeRange"];
      if (obj.time.length == 2) {
        obj.startTime = obj.time[0];
        obj.endTime = obj.time[1];
      }
      delete obj.time
      // 请求数据
      this.$api.getActivityInfoListByParams(obj).then((res) => {
        this.commonUtil.tableAssignment(
          res.data.page,
          this.pageData.tablePage,
          this.pageData.tableData
        );
      })
      .finally(()=>{
        this.loading=false;
      })
    },
    // 重置
    resetSearch() {
      this.commonUtil.clearObj(this.pageData.queryData);
      this.searchTableList();
    },
    /**
     * @description: modal显示
     * @param {type} 类型 1新增，2编辑 3详情
     * @param {id} 数据唯一标识
     * @return:
     * @author: ym
     */
    showModal(type, row) {
      this.commonUtil.clearObj(this.pageData.modalData); //清空modalData
      this.$nextTick(()=>{
        this.$refs["modalRef"].$refs["modalFormRef"].clearValidate(); //校验重置
      })
      this.pageData.modalData.source=this.$newSource//获取默认的资讯来源
      this.pageData.modalData.isVideo='0'//补充isVideo 不会触发watch
      this.commonUtil.showModal(this.pageData.modalConfig, type);
      if (type != this.commonConstants.modalType.insert) {
        this.getDetail(row);
      }
    },
    /**
     * @description: 获取详细数据
     * @param {id} 数据唯一标识
     * @return:
     * @author: ym
     */
    getDetail(row) {
     if(row.imageUrl){
        row.fileList=[{
        url:row.imageUrl
      }]
      }
      if(row.videoUrl){
        row.fileListVideo=[{
          url:row.videoUrl
          // +'?x-oss-process=video/snapshot,t_10000,m_fast'
        }]
      }
      row.isVideo=row.isVideo+''
      this.$nextTick(()=>{
        this.pageData.modalData = JSON.parse(JSON.stringify(row));
      })
    },
    /**
     * @description: 关闭modal
     * @param
     * @return:
     * @author: ym
     */
    closeModal() {
      this.pageData.modalConfig.show = false; //关闭modal
    },
    /**
     * @description: 保存数据
     * @param {type}
     * @return:
     * @author: ym
     */
    save() {
      this.pageData.modalData.userId = this.$store.state.user.id;
      this.$refs["modalRef"].$refs["modalFormRef"].validate((valid) => {
        if (valid) {
          let content = this.pageData.modalData;
          if(content.isVideo==0){
            content.videoUrl=''
          }
          if (
            this.pageData.modalConfig.type ==
            this.commonConstants.modalType.insert
          ) {
            this.$api.saveActivityInfo(content).then((res) => {
              this.searchTableList();
            });
          } else {
            this.$api.updateRedActivityInfo(content).then((res) => {
              this.searchTableList();
            });
          }
          this.closeModal();
        } else {
          return false;
        }
      });
    },
    /**
     * @description: 删除一条数据
     * @param {id} 数据唯一标识
     * @return:
     * @author: ym
     */
    deleteOne(id) {
      let ids = [];
      ids[0] = id;
      let obj = {
        messageContent: this.commonUtil.getMessageFromList(
          "confirm.delete",
          null
        ),
      };
      this.commonUtil
        .showConfirm(obj)
        .then(async () => {
          await this.$api.deleteRedActivityInfo(ids).then((res) => {
            this.searchTableList();
          });
        })
        .catch(() => {
          this.commonUtil.showMessage({
            message: this.commonUtil.getMessageFromList("error.cancel", null),
            type: this.commonConstants.messageType.info,
          });
        });
    },
    /**
     * @description: 批量删除
     * @param {type}
     * @return:
     * @author: ym
     */
    deleteBatch() {
      const length = this.pageData.selectList.length;
      if (length == 0) {
        this.commonUtil.showMessage({
          message: this.commonUtil.getMessageFromList(
            "error.batchdelete.empty",
            null
          ),
          type: this.commonConstants.messageType.error,
        });
      } else {
        let ids = [];
        for (let i = 0; i < length; i++) {
          ids.push("" + this.pageData.selectList[i].contentInfoId);
        }
        let obj = {
          messageContent: this.commonUtil.getMessageFromList(
            "confirm.delete",
            null
          ),
        };
        this.commonUtil
          .showConfirm(obj)
          .then(() => {
            this.$api.deleteRedActivityInfo(ids).then((res) => {
              this.searchTableList();
            });
          })
          .catch(() => {
            this.commonUtil.showMessage({
              message: this.commonUtil.getMessageFromList("error.cancel", null),
              type: this.commonConstants.messageType.info,
            });
          });
      }
    },
    selectChange(rows) {
      this.pageData.selectList = rows;
    },
  },
};
</script>
<style lang="scss" scoped>
  .content-dialog ::v-deep .el-dialog__body{
    padding: 0px;
  }
</style>