<template>
  <div class="advertising-banner">
    <div class="top">
      <div>
        <mySelect
            label="name"
            id="id"
            placeholder="请选择页面"
        ></mySelect>
        <el-button class="btn-search" size="medium" type="primary" @click="handleSearch">查询</el-button>
      </div>
      <div>
        <el-button size="medium" @click="handleAddNews">新增</el-button>
        <el-button size="medium" type="primary" @click="handleDelete">删除
        </el-button>
      </div>
    </div>
    <myTable
        class="my-table"
        @editor="handleEditor"
        @select-change="handleSelectChange"
    />
    <myPagination
        class="my-Pagination"
        :pageSizes="defaultPageSizes"
        @size-change="handleSizeChange"
        @current-page="handleCurrentPage"
    />

    <!--    弹窗 新增   -->
    <el-dialog
        title="新增广告"
        :visible.sync="addDialogVisit"
        width="30%"
        @close="handleResetAdvertising('addForm')"
        center>
      <div class="add-dialog-content">
        <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="80px" class="demo-ruleForm">
          <el-form-item label="页面:" prop="code">
            <el-select v-model="addForm.code" placeholder="请选择页面">
              <el-option
                  v-for="item in myMenu"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="序号:" prop="sort">
            <el-input v-model="addForm.sort"></el-input>
          </el-form-item>
          <el-form-item label="链接:" prop="url">
            <el-input v-model="addForm.url"></el-input>
          </el-form-item>
          <el-form-item label="图片:" prop="pic">
            <upload-file :imageUrl="addForm.pic"
                         :showBtnFlag="false"
                         @getFileUrl="getAddImageUrl"></upload-file>
            <h5 class="picture-size-h5">（最佳尺寸为{{ addText }}像素）</h5>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
                <el-button size="medium" @click="addDialogVisit = false">取 消</el-button>
                <el-button size="medium" type="primary" @click="handleAddAdvertising('addForm')">确 定</el-button>
            </span>
    </el-dialog>

    <!--    弹窗 编辑   -->
    <el-dialog
        title="编辑广告"
        :visible.sync="editorDialogVisit"
        width="30%"
        @close="handleEditorResetAdvertising('editorForm')"
        @open="handleGetAdvertisingInfo"
        center>
      <div class="add-dialog-content">
        <el-form :model="editorForm" :rules="editorRules" ref="editorForm" label-width="80px"
                 class="demo-ruleForm">
          <el-form-item label="页面:" prop="code">
            <el-select v-model="editorForm.code" placeholder="请选择页面">
              <el-option
                  v-for="item in myMenu"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="序号:" prop="sort">
            <el-input v-model="editorForm.sort"></el-input>
          </el-form-item>
          <el-form-item label="链接:" prop="url">
            <el-input v-model="editorForm.url"></el-input>
          </el-form-item>
          <el-form-item label="图片:" prop="pic">
            <upload-file :imageUrl="editorForm.pic"
                         :showBtnFlag="false"
                         @getFileUrl="getEditorImageUrl"></upload-file>
            <h5 class="picture-size-h5">（最佳尺寸为{{ editorText }}像素）</h5>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
                <el-button size="medium" @click="editorDialogVisit = false">取 消</el-button>
                <el-button size="medium" type="primary" @click="handleEditorAdvertising('editorForm')">确 定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
import uploadFile from '@/components/Admin/Common/uploadFile';
import myPagination from './components/Pagination';
import myTable from './components/Table';
import mySelect from './components/Select';
import * as HFGG from '@/api/banner';
import * as comminUtil from '@/utils/admin/tools';
import Vue from 'vue';

// 菜单
const menu = [
  {
    id: 1,
    name: '首页',
    size: '1920 * 1920'
  },
  {
    id: 2,
    name: '考试系统',
    size: '1920 * 1920'
  },
  {
    id: 3,
    name: '培训系统',
    size: '1920 * 1920'
  },
  {
    id: 4,
    name: '课程定制',
    size: '1920 * 1920'
  },
  {
    id: 5,
    name: '课程资源',
    size: '1920 * 1920'
  },
  {
    id: 6,
    name: '严肃考试',
    size: '1920 * 1920'
  },
  {
    id: 7,
    name: '企业培训',
    size: '1920 * 1920'
  },
  {
    id: 8,
    name: '万人高并发',
    size: '1920 * 1920'
  },
  {
    id: 9,
    name: '私有化部署',
    size: '1920 * 1920'
  },
  {
    id: 10,
    name: '政府机构',
    size: '1920 * 1920'
  },
  {
    id: 11,
    name: '教育机构',
    size: '1920 * 1920'
  },
  {
    id: 12,
    name: '能源化工',
    size: '1920 * 1920'
  },
  {
    id: 13,
    name: '金融保险',
    size: '1920 * 1920'
  },
  {
    id: 14,
    name: '食品餐饮',
    size: '1920 * 1920'
  },
  {
    id: 15,
    name: '交通运输',
    size: '1920 * 1920'
  },
  {
    id: 16,
    name: '医疗保险',
    size: '1920 * 1920'
  },
  {
    id: 17,
    name: '新闻资讯',
    size: '1920 * 1920'
  },
  {
    id: 18,
    name: '关于我们',
    size: '1920 * 1920'
  },
  {
    id: 19,
    name: '职业素养',
    size: '1920 * 1920'
  },
  {
    id: 20,
    name: '领导能力',
    size: '1920 * 1920'
  },
  {
    id: 21,
    name: '人力资源',
    size: '1920 * 1920'
  },
  {
    id: 22,
    name: '市场营销',
    size: '1920 * 1920'
  },
  {
    id: 23,
    name: '行政管理',
    size: '1920 * 1920'
  },
  {
    id: 24,
    name: '财务管理',
    size: '1920 * 1920'
  },
  {
    id: 25,
    name: '客服服务',
    size: '1920 * 1920'
  },
  {
    id: 26,
    name: '产品运营',
    size: '1920 * 1920'
  },
  {
    id: 27,
    name: '生产采购',
    size: '1920 * 1920'
  },
];
const CHANGEPAGECODE = {
  add: 'add',
  editor: 'editor',
};
const selectData = {
  options: menu,
  id: null,
};
const tableData = {
  myData: [],
};
const pagination = {
  page: 1,
  size: 10,
  total: 0,
};
const defaultPageSizes = [10, 20, 30, 40];
const tableServiceData = Vue.observable(tableData);
const selectServiceData = Vue.observable(selectData);
const paginationServiceData = Vue.observable(pagination);

export default {
  name: 'Advertising',
  provide: {
    tableServiceData,
    paginationServiceData,
    selectServiceData,
  },
  components: {
    myPagination,
    myTable,
    mySelect,
    uploadFile,
  },
  data() {
    return {
      defaultPageSizes: defaultPageSizes,
      curIiId: null,
      tableSelectData: [],
      addDialogVisit: false,
      editorDialogVisit: false,
      addForm: {
        code: null,
        sort: '',
        url: '',
        pic: '',
      },
      addRules: {
        code: [
          {required: true, message: '页面不能为空', trigger: 'blur'},
        ],
        pic: [
          {required: true, message: '图片不能为空', trigger: 'blur'},
        ],
      },
      editorForm: {
        code: null,
        sort: '',
        url: '',
        pic: '',
      },
      editorRules: {
        code: [
          {required: true, message: '页面不能为空', trigger: 'blur'},
        ],
        pic: [
          {required: true, message: '图片不能为空', trigger: 'blur'},
        ],
      },
      userId: null,
      selectRow: null,
    };
  },
  computed: {
    addText() {
      const code = this.addForm.code;
      console.log(code);
      if (code) {
        console.log(menu.filter(item => item.id === code))
        return menu.filter(item => item.id === code)[0].size;
      } else {
        return `? * ?`
      }
    },
    editorText() {
      const code = this.editorForm.code;
      console.log(code);
      if (code) {
        console.log(menu.filter(item => item.id === code))
        return menu.filter(item => item.id === code)[0].size;
      } else {
        return `? * ?`
      }
    },
    myMenu() {
      return menu;
    },
    myPage() {
      return paginationServiceData.page;
    },
    mySize() {
      return paginationServiceData.size;
    },
    myTotal() {
      return paginationServiceData.total;
    },
  },
  methods: {
    handleSearch() {
      paginationServiceData.page = 1;
      this.searchAdvertisingData();
    },
    handleEditor(data) {
      this.selectRow = data;
      this.editorDialogVisit = true;
    },
    async handleDelete() {
      if (!this.tableSelectData.length) {
        this.$message.warning('请选择至少一条需要删除的数据');
        return;
      }

      const opt = {
        bnIds: [...this.tableSelectData],
      };

      const loading = this.$loading({background: 'rgba(0, 0, 0, 0.7)'});
      try {
        const res = await HFGG.getBannerDelete(opt);
        loading.close();
        if (res.code === 0 && res.data) {
          // 删除成功重置选择状态
          this.tableSelectData = [];
          // 刷新页面
          const newOpt = this.getOption();
          const res = await HFGG.getBannerList(newOpt);
          if (res.code === 0) {
            this.initPageData(res.data);
          }
          loading.close();
        }
      } catch (err) {
        loading.close();
      }
    },
    handleSelectChange(data) {
      this.tableSelectData = data;
    },
    handleAddNews() {
      this.addDialogVisit = true;
    },
    searchAdvertisingData() {
      const opt = this.getOption();
      const loading = this.$loading({background: 'rgba(0, 0, 0, 0.7)'});
      HFGG.getBannerList(opt)
          .then(res => {
            this.initPageData(res.data);
            loading.close();
          })
          .catch(err => {
            loading.close();
          });
    },
    handleSizeChange(size) {
      paginationServiceData.size = size;
      this.searchAdvertisingData();
    },
    handleCurrentPage(page) {
      paginationServiceData.page = page;
      this.searchAdvertisingData();
    },
    handleEditorAdvertising(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.editorAdvertisingFun();
        } else {
          return false;
        }
      });
    },
    async editorAdvertisingFun() {
      const loading = this.$loading({background: 'rgba(0, 0, 0, 0.7)'});
      try {
        const opt = Object.assign({}, this.editorForm, {userId: this.userId, bnId: this.selectRow.bnId});
        const res = await HFGG.getBannerUpdate(opt);
        if (res.code === 0) {
          this.editorDialogVisit = false;
          const opt = this.getOption();
          const myData = await HFGG.getBannerList(opt);
          this.initPageData(myData.data);
        }
        loading.close();
      } catch (e) {
        loading.close();
      }
      this.addDialogVisit = false;
    },
    handleEditorResetAdvertising(formName) {
      this.$refs[formName].resetFields();
      this.editorDialogVisit = false;
    },
    handleGetAdvertisingInfo() {
      const opt = {bnId: this.selectRow.bnId};
      const loading = this.$loading({background: 'rgba(0, 0, 0, 0.7)'});
      HFGG.getBannerInfo(opt)
          .then(res => {
            console.log(res);
            const {name, url, pic, sort, code} = res.data;
            this.editorForm.name = name;
            this.editorForm.url = url;
            this.editorForm.pic = pic;
            this.editorForm.sort = sort;
            this.editorForm.code = code;
            loading.close();
          })
          .catch(err => {
            loading.close();
          });
    },
    getEditorImageUrl(url) {
      this.editorForm.pic = url;
    },
    handleResetAdvertising(formName) {
      this.$refs[formName].resetFields();
      this.addDialogVisit = false;
    },
    handleAddAdvertising(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addAdvertisingFun();
        } else {
          return false;
        }
      });
    },
    async addAdvertisingFun() {
      const loading = this.$loading({background: 'rgba(0, 0, 0, 0.7)'});
      try {
        const opt = Object.assign({}, this.addForm, {userId: this.userId});
        const res = await HFGG.getBannerAdd(opt);
        if (res.code === 0) {
          this.addDialogVisit = false;
          const opt = this.getOption();
          const myData = await HFGG.getBannerList(opt);
          this.initPageData(myData.data);
          loading.close();
        }
      } catch (e) {
        loading.close();
      }
      this.addDialogVisit = false;
    },
    getOption() {
      const opt = {
        code: selectServiceData.id,
        page: this.myPage,
        size: this.mySize,
      };
      return opt;
    },
    // 渲染页面
    initPageData(listData) {
      tableServiceData.myData = listData.data;
      paginationServiceData.total = listData.total;
    },
    // 初始化页面
    async initPageService() {
      const loading = this.$loading({background: 'rgba(0, 0, 0, 0.7)'});
      try {
        // 新闻资讯列表
        const opt = this.getOption();
        const {code, data} = await HFGG.getBannerList(opt);
        loading.close();
        if (code === 0) {
          // 渲染页面
          this.initPageData(data);
        }
      } catch (e) {
        loading.close();
      }
    },
    clearPageData() {
      selectServiceData.options = [];
      selectServiceData.id = null;
      tableServiceData.myData = [];
      paginationServiceData.page = 1;
      paginationServiceData.size = 10;
      paginationServiceData.total = 0;
    },
    getAddImageUrl(url) {
      this.addForm.pic = url;
    },
  },
  created() {
    const userAuth = comminUtil.getUserAuth();
    this.userId = userAuth && userAuth.userId ? userAuth.userId : null;
  },
  mounted() {
    this.initPageService();
  },
  beforeDestroy() {
    this.clearPageData();

  },
};
</script>

<style lang="scss" scoped>
.advertising-banner {
  padding: 20px;

  .top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;

    .btn-search {
      margin-left: 20px;
    }
  }

  .my-table {
    height: calc(100vh - 270px) !important;
  }

  .my-Pagination {
    margin-top: 20px;
  }

  .add-dialog-content {
    .el-select {
      width: 100%;
    }
  }
}
</style>
