<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot-scope="{type,size}" slot="activeIdSearch">
        <el-select @change="searchStateChange" v-model="query.activeId"
                   :loading="loading"
                   filterable
                   remote
                   reserve-keyword
                   placeholder="请输入关键词"
                   :remote-method="searchActiveList">
          <el-option
            v-for="item in searchActiveOption"
            :key="item.id"
            :label="item.title"
            :value="item.id">
          </el-option>
        </el-select>
      </template>
      <template slot-scope="{type,size}" slot="createTimeSearch">
        <el-radio-group v-model="query.createTime" :size="size" style="float: left">
          <el-radio-button @click="searchStateChange" :label="-1">全部</el-radio-button>
          <el-radio-button @click="searchStateChange" :label="1">今天</el-radio-button>
          <el-radio-button @click="searchStateChange" :label="2">昨天</el-radio-button>
          <el-radio-button @click="searchStateChange" :label="3">最近七天</el-radio-button>
          <el-radio-button @click="searchStateChange" :label="4">最近30天</el-radio-button>
          <el-radio-button @click="searchStateChange" :label="5">本月</el-radio-button>
          <el-radio-button @click="searchStateChange" :label="6">本年</el-radio-button>
        </el-radio-group>
        <avue-date v-model="query.createTimeRange" type="datetimerange" format="yyyy年MM月dd日 hh:mm:ss"
                   value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择日期"
                   :size="size"
                   @change="searchStateChange"
                   style="width: 280px;margin-left:5px;float: left"
                   range-separator="-"
                   start-placeholder="开始日期"
                   end-placeholder="结束日期"></avue-date>
      </template>
      <template slot-scope="{type,size}" slot="statusSearch">
        <el-radio-group v-model="query.status" :size="size" @change="searchStateChange">
          <el-radio-button :label="select.value" v-for="(select,index) in [{
            label:'全部',
            value:-1
          }].concat(option.column.find(ele=>{
            return ele.prop==='status';
          }).dicData)" :key="index">{{ select.label }}
          </el-radio-button>
        </el-radio-group>
      </template>
      <template slot-scope="{type,size}" slot="keySearch">
        <el-input type="text" placeholder="请输入作品标题或编号" v-model="query.key" :size="size"
                  style="width: 300px;margin: 1px 5px 1px 0;">
          <el-button type="primary" :size="size" icon="el-icon-search" slot="append"
                     @click="searchStateChange"></el-button>
        </el-input>
        <!--        <el-button type="primary" :size="size" icon="el-icon-top" @click="generateListAndDownload">生成列表[后端]</el-button>-->
        <el-button type="primary" :size="size" icon="el-icon-top" @click="generateListAndDownloadOfWeb">生成列表</el-button>
        <!--        <el-button type="primary" :size="size">导出已生成列表</el-button>-->
      </template>
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.activeproductrecord_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>

      <template slot="menu" slot-scope="{row}">
        <el-button type="text" size="small" icon="el-icon-view" @click="checkVote(row)">投票ip情况</el-button>
        <el-button type="text" size="small" icon="el-icon-refresh-right" @click="editVote(row)">刷新票数</el-button>
      </template>
    </avue-crud>

    <el-dialog title="作品投票情况"
               append-to-body
               :visible.sync="voteVisible"
               width="75%">
      <div v-if="voteVisible">
        <product-help-vote :product-id="voteProductId"></product-help-vote>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {add, generateList, getDetail, getList, remove, update,editCount} from "@/api/sing_active/activeproductrecord";

  import {getList as getActiveList, getDetail as getActiveRecordDetail} from "@/api/sing_active/activerecord";
  import {mapGetters} from "vuex";
  import moment from "moment";
  import IconFontComp from "@/views/base/iconfont";
  import FileUtil from "@/util/fileUtil";
  import ProductHelpVote from "./producthelpvote";

  export default {
    components: {ProductHelpVote, IconFontComp},
    data() {
      return {
        voteProductId: '',
        voteVisible: false,

        form: {},
        searchActiveOption: [],
        query: {
          createTime: -1,
          createTimeRange: [],
          status: -1,
        },
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          searchBtn: false,
          emptyBtn: false,
          viewBtn: true,
          labelWidth: 120,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "用户手机",
              prop: "phone",
              // type: "select",
              // dicUrl:"/api/sing_user/loginuser/list?current=1&size=999",
              // props: {
              //   label: 'nickName',
              //   value: 'phone',
              //   desc: 'phone',
              //   res: "data.records"
              // },
              // dicMethod:'get',
              rules: [{
                required: true,
                message: "请输入手机号码",
                trigger: "blur"
              }]
            },
            {
              label: "参赛者",
              prop: "player",
              rules: [{
                required: true,
                message: "请输入参赛者",
                trigger: "blur"
              }]
            },
            {
              label: "活动",
              prop: "activeId",
              search: true,
              hide: true,
              searchslot: true,
              control: (val, form) => {
                return this.controlActiveField(val, form);
              },
              searchSpan: 12,
              searchOrder: 0,
              type: "select",
              dicUrl: "/api/sing_active/activerecord/list?current=1&size=999",
              props: {
                label: 'title',
                value: 'id',
                desc: 'id',
                res: "data.records"
              },
              dicMethod: 'get',
              rules: [{
                required: true,
                message: "请输入活动Id",
                trigger: "blur"
              }]
            },
            {
              label: "活动名称",
              prop: "activeName",
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "类型",
              prop: "type",
              type: "select",
              hide: true,
              disabled: true,
              control: (value) => {
                const result = {
                  videoUrl: {
                    editDisplay: false,
                    addDisplay: false,
                  }
                }
                if (value === "VIDEO_TEXT") {
                  result.videoUrl = {
                    editDisplay: true,
                    addDisplay: true,
                  }
                }
                return result;
              },
              dicData: [
                {
                  label: "视频文本",
                  value: "VIDEO_TEXT"
                },
                {
                  label: "图片文本",
                  value: "IMAGE_TEXT"
                }
              ],
              rules: [{
                required: true,
                message: "请输入类型",
                trigger: "blur"
              }]
            },
            {
              label: "作品编号",
              prop: "productNo",
              editDisplay: false,
              addDisplay: false,
              rules: [{
                required: true,
                message: "请输入作品编号",
                trigger: "blur"
              }]
            },
            {
              label: "标题",
              prop: "title",
              rules: [{
                required: true,
                message: "请输入标题",
                trigger: "blur"
              }]
            },
            {
              label: "活动图片地址",
              prop: "imgUrl",
              type: 'upload',
              listType: 'picture-img',
              dataType: 'string',
              span: 12,
              propsHttp: {
                res: 'data',
                url: 'link'
              },
              action: '/api/blade-resource/oss/endpoint/put-file',
              rules: [{
                required: true,
                message: "请输入活动图片地址",
                trigger: "blur"
              }]
            },
            {
              label: "活动视频地址",
              prop: "videoUrl",
              type: 'upload',
              listType: 'picture-img',
              dataType: 'string',
              accept: "video/mp4",
              span: 12,
              propsHttp: {
                res: 'data',
                url: 'link'
              },
              action: '/api/blade-resource/oss/endpoint/put-file',
              rules: [{
                required: true,
                message: "请输入活动视频地址",
                trigger: "blur"
              }]
            },
            {
              label: "票数",
              prop: "voteCount",
              type: "number",
              value: 0,
              rules: [{
                required: true,
                message: "请输入票数",
                trigger: "blur"
              }]
            },
            /*{
              label: "热力值",
              prop: "heatValue",
              type: "number",
              value: 0,
              rules: [{
                required: true,
                message: "请输入热力值",
                trigger: "blur"
              }]
            },*/
            {
              label: "作品状态",
              prop: "status",
              search: true,
              searchSpan: 24,
              searchslot: true,
              searchOrder: 2,
              type: "switch",
              dicData: [
                {
                  label: "禁用",
                  value: 0
                },
                {
                  label: "启用",
                  value: 1,
                }
              ],
              value: 1,
              rules: [{
                required: true,
                message: "请开启或关闭状态",
                trigger: "blur"
              }]
            },
            {
              label: "作品内容",
              prop: "content",
              component: 'AvueUeditor',
              options: {
                action: '/api/blade-resource/oss/endpoint/put-file',
                props: {
                  res: "data",
                  url: "link",
                }
              },
              hide: true,
              minRows: 6,
              span: 24,
              rules: [{
                required: true,
                message: "请输入活动内容",
                trigger: "blur"
              }]
            },
            {
              label: "创建时间",
              prop: "createTime",
              type: "datetime",
              format: "yyyy-MM-dd HH:mm:ss",
              valueFormat: "yyyy-MM-dd HH:mm:ss",
              searchRange: true,
              addDisplay: false,
              editDisplay: false,
              search: true,
              searchSpan: 24,
              searchOrder: 0,
              searchslot: true,
              rules: [{
                required: true,
                message: "请输入通知时间",
                trigger: "blur"
              }]
            },
            {
              label: "关键字",
              prop: "key",
              hide: true,
              search: true,
              searchslot: true,
              searchOrder: 5,
              searchSpan: 24,
              editDisplay: false,
              addDisplay: false,
            },
          ]
        },
        data: []
      };
    },
    watch: {
      //监听创建时间变化
      "query.createTime": {
        handler(value) {
          //防止重复调用
          if (value !== undefined) {
            this.query.createTimeRange = [];
            switch (value) {
              case -1:
                this.query.createTimeStart = undefined;
                this.query.createTimeEnd = undefined;
                break;
              case 1: //今天
                this.query.createTimeStart = moment().format("yyyy-MM-DD 00:00:00");
                this.query.createTimeEnd = moment().format("yyyy-MM-DD HH:mm:ss");
                break;
              case 2: //昨天
                this.query.createTimeStart = moment().subtract(1, 'days').format("yyyy-MM-DD 00:00:00");
                this.query.createTimeEnd = moment().subtract(1, 'days').format("yyyy-MM-DD 23:59:59");
                break;
              case 3: //近7天
                this.query.createTimeStart = moment().subtract(7, 'days').format("yyyy-MM-DD HH:mm:ss");
                this.query.createTimeEnd = moment().format("yyyy-MM-DD HH:mm:ss");
                break;
              case 4: //近30天
                this.query.createTimeStart = moment().subtract(30, 'days').format("yyyy-MM-DD HH:mm:ss");
                this.query.createTimeEnd = moment().format("yyyy-MM-DD HH:mm:ss");
                break;
              case 5: //本月
                this.query.createTimeStart = moment().format("yyyy-MM-01 00:00:00");
                this.query.createTimeEnd = moment().format(`yyyy-MM-DD HH:mm:ss`);
                break;
              case 6: //本年
                this.query.createTimeStart = moment().format("yyyy-01-01 00:00:00");
                this.query.createTimeEnd = moment().format(`yyyy-MM-DD HH:mm:ss`);
                break;
              default:
                break;
            }
          }
        }
      },
      //监听创建时间变化
      "query.createTimeRange": {
        handler(value) {
          //防止重复调用
          if (value.length === 2) {
            this.query.createTimeStart = value[0];
            this.query.createTimeEnd = value[1];
            this.query.createTime = undefined;
          }
        }
      },
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.activeproductrecord_add, false),
          viewBtn: this.vaildData(this.permission.activeproductrecord_view, false),
          delBtn: this.vaildData(this.permission.activeproductrecord_delete, false),
          editBtn: this.vaildData(this.permission.activeproductrecord_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    created() {
      this.searchActiveList();
    },
    methods: {
      editVote(row){
        editCount(row.id).then(res => {
          if (res.data.success){
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }
        })
      },
      checkVote(row) {
        this.voteProductId = row.id;
        this.voteVisible = true;
      },
      searchActiveList(value) {
        getActiveList(1, 999, {
          title: value,
        }).then(res => {
          this.searchActiveOption = res.data.data.records;
        });
      },
      controlActiveField(value, form) {
        if (value) {
          getActiveRecordDetail(value).then(res => {
            form.type = res.data.data.type;
          });
        }
        return {};
      },
      rowSave(row, done, loading) {
        row.content = encodeURIComponent(row.content);
        if (row.videoUrl && row.videoUrl.constructor == Array) {
          row.videoUrl = row.videoUrl.join();
        }
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        row.content = encodeURIComponent(row.content);
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            res.data.data.content = decodeURIComponent(res.data.data.content);
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        // this.query = {};
        this.onLoad(this.page, this.query);
      },
      searchChange(params, done) {
        this.page.currentPage = 1;
        this.onLoad(this.page, this.query);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        let values = {};
        Object.assign(params, this.query)
        for (const item in params) {
          if (params[item] && params[item] !== -1) {
            values[item] = params[item];
          }
        }
        values.createTime = null;
        values.createTimeRange = null;
        this.loading = true;
        getList(page.currentPage, page.pageSize, values).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      //搜索状态改变
      searchStateChange() {
        setTimeout(() => {
          this.onLoad(this.page, this.query);
        }, 100);
      },
      //生成列表并到处
      generateListAndDownload() {
        const newQuery = {};
        for (const item in this.query) {
          if (this.query[item] !== undefined && this.query[item] !== -1) {
            newQuery[item] = this.query[item];
          }
        }
        newQuery.createTime = null;
        newQuery.createTimeRange = null;
        //获取列表键值对
        newQuery.keyValue = {};
        this.option.column.forEach(ele => {
          newQuery.keyValue[ele.prop] = ele.label;
        });
        newQuery.keyValue = JSON.stringify(newQuery.keyValue);
        this.loading = true;
        //生成列表
        generateList(this.page.currentPage, this.page.pageSize, newQuery).then(res => {
          FileUtil.download(res.data, {
            type: "application/vnd.ms-excel"
          }, `生成活动作品-${moment().format("yyyy-MM-DD HH:mm:ss")}.xls`);
        }).finally(() => {
          this.loading = false;
        });
      },
      generateListAndDownloadOfWeb() {
        const filterArray = ["关键字", "类型", "作品内容"];
        this.$Export.excel({
          title: `活动作品数据导出-${moment().format("yyyy-MM-DD HH:mm:ss")}`,
          columns: this.option.column.filter(ele => {
            return filterArray.indexOf(ele.label) === -1;
          }),
          data: this.selectionList.length !== 0 ? this.selectionList : this.data
        });
      }
    }
  };
</script>

<style>
</style>
