<template>
  <div class="app-container">
    <el-form ref="mainForm" :model="mainForm" :rules="mainFormRules" label-width="110px" label-position="right">
      <el-form-item label="水印名称" prop="name">
        <el-input v-model="mainForm.name" placeholder="请输入水印名称" style="width: 300px"></el-input>
      </el-form-item>

      <el-form-item label="水印图片" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          style="height:122px"
          :action="baseURL + 'common/upload'"
          :headers="myHeaders"
          :show-file-list="false"
          :on-success="uploadSuccess7"
          :before-upload="beforeUpload7">
          <img v-if="mainForm.logoUrl" :src="mainForm.logoUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="水印显示日期" prop="showDate">
        <el-date-picker
          v-model="mainForm.showDate"
          style="width: 300px"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable>
        </el-date-picker>
      </el-form-item>
    </el-form>

    <div class="mymain-container">
      <div class="btn-group">
        <el-button size="small" type="primary" @click="addClassify">选择分类</el-button>
        <el-button size="small" type="primary" @click="addGoods">选择商品</el-button>
      </div>

      <div class="table">
        <el-table :data="goodsList" border fit stripe>
          <el-table-column align="center" label="商品名称" prop="goodsName" min-width="200"></el-table-column>
          <el-table-column align="center" label="销售价格" prop="goodsPrice" min-width="110">
            <template slot-scope="scope">
              ¥{{ scope.row.goodsPrice }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="分销金额" prop="shareAmount" min-width="110">
            <template slot-scope="scope">
              ¥{{ scope.row.shareAmount }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="库存" prop="stockNum"></el-table-column>
          <el-table-column align="center" label="销量" prop="soldNum"></el-table-column>
          <el-table-column align="center" label="状态" class-name="status-col">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status ? 'success':'danger'">{{ scope.row.status ? '上架':'下架' }}</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="deleteGoods(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="page-footer">
      <div class="footer" :class="classObj">
        <el-button type="primary" @click="submitForm" :loading="formLoading">{{ formLoading ? '提交中 ...' : '提 交' }}</el-button>
        <el-popconfirm
          title="确定关闭吗？"
          @confirm="goBack"
          style="margin-left: 10px;"
        >
          <el-button slot="reference">关 闭</el-button>
        </el-popconfirm>
      </div>
    </div>

    <!-- 选择商品 -->
    <el-dialog title="选择商品" :visible.sync="addGoodsVisible" :show-close="false" width="50%" :close-on-click-modal="false">
      <div class="dialog-container clearfix">
        <div class="left fl">
          <div class="item" @click="changeClassify('')">全部分类</div>
          <div class="group" v-for="(item, index) in classifyList" :key="index">
            <div class="item" @click="toggleOpen(index)">
              <i :class="item.isOpen ? 'el-icon-caret-bottom':'el-icon-caret-right'"></i> {{item.name}}
            </div>
            <div class="child" v-if="item.isOpen">
              <div class="item" v-for="(childItem, childIndex) in item.children" :key="childIndex" @click="changeClassify(childItem.categoryId)">{{childItem.name}}</div>
            </div>
          </div>
        </div>

        <div class="right fl">
          <div class="search">
            <el-input placeholder="请输入商品名称进行搜索" v-model="keyword" class="input-with-select" clearable size="small" style="width: 250px">
              <el-button slot="append" icon="el-icon-search" size="small" @click="getGoodsListByScreen"></el-button>
            </el-input>
          </div>
          <div class="table" style="margin: 10px 0 20px;">
            <el-table 
              v-loading="table_listLoading" 
              :data="table_dataList" 
              element-loading-text="Loading" 
              tooltip-effect="dark" 
              style="width: 100%" 
              max-height="270"
              @selection-change="handleChooseGoods">
              <el-table-column align="center" type="selection" :selectable='checkboxSelect' width="45"></el-table-column>
              <el-table-column align="center" prop="goodsName" label="商品名称" min-width="200" show-overflow-tooltip></el-table-column>
              <el-table-column align="center" prop="goodsPrice" label="价格" width="80"></el-table-column>
              <el-table-column align="center" prop="stockNum" label="库存" width="80"></el-table-column>
            </el-table>
          </div>
          <div class="pagination clearfix">
            <div class="fr">
              <el-pagination
                @current-change="handleTableCurrentChange"
                :current-page="table_currentPage"
                :page-size="table_pageSize"
                background
                layout="prev, pager, next"
                :total="table_listTotal">
              </el-pagination>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddGoods">保 存</el-button>
        <el-button @click="cancelAddGoods">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择分类 -->
    <el-dialog title="选择分类" :visible.sync="addClassifyVisible" :show-close="false" width="40%" :close-on-click-modal="false">
      <div class="classify-list">
        <el-tree
          :data="classifyList"
          show-checkbox
          default-expand-all
          node-key="categoryId"
          ref="tree"
          highlight-current
          :props="defaultProps">
        </el-tree>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddClassify">保 存</el-button>
        <el-button @click="cancelAddClassify">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { getModuleDetail, addModule, editModule, getClassifyList, getGoodsList, getMoreGoodsList } from '@/api/goods'

export default {
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: {'x-token': getToken()},
      isEdit: false,
      editId: '',

      mainForm: {
        name: '',
        logoUrl: '',
        showDate: [],
      },
      mainFormRules: {
        name: [
          { required: true, message: '请输入水印名称', trigger: 'blur' }
        ],
        logoUrl: [
          { required: true, message: '请上传水印图片', trigger: 'blur' }
        ],
        showDate: [
          { required: true, message: '请选择水印显示日期', trigger: 'blur' }
        ],
      },

      formLoading: false,

      goodsList: [], // 列表数据
      addGoodsVisible: false,

      classifyList: [],
      classifyCurrent: '',
      keyword: '',
      table_dataList: null, // 列表数据
      table_listLoading: true, // 列表加载loading
      table_currentPage: 1, // 当前页码
      table_pageSize: 10, // 每页数量
      table_listTotal: 0, // 列表总数
      table_chooseGoods: [], // table中 当前选择商品

      addClassifyVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened
      }
    },
  },

  created() {
    const { id } = this.$route.query;
    this.isEdit = id ? true : false;
    this.editId = id;

    if(this.isEdit) {
      this.getModuleDetail(id);
    }
  },

  methods: {
    // 获取详情
    getModuleDetail(commonTemplateId) {
      getModuleDetail({commonTemplateId}).then(res => {
        this.mainForm = {
          name: res.data.name,
          content: res.data.content,
          logoUrl: res.data.logo,
          showDate: res.data.logoStartTime ? [res.data.logoStartTime.slice(0, 10), res.data.logoEndTime.slice(0, 10)] : [],
        }
        this.goodsList = res.data.goodsList
      })
    },

    // 获取分类列表
    getClassifyList() {
      getClassifyList({categoryLevel: 1, status: true}).then(res => {
        res.data.forEach(item => {
          item.isOpen = false;
        });
        this.classifyList = res.data;
        this.classifyCurrent = '';
        this.getGoodsList();
      })
    },

    // 展开/收起 分类
    toggleOpen(index) {
      this.classifyList[index].isOpen = !this.classifyList[index].isOpen;
    },

    // 切换分类
    changeClassify(cid) {
      if(this.table_chooseGoods.length > 0) {
        return this.$errorMsg('当前已选择商品，不可切换分类');
      }
      this.classifyCurrent = cid;
      this.table_currentPage = 1;
      this.getGoodsList();
    },

    // 搜索
    getGoodsListByScreen() {
      if(this.table_chooseGoods.length > 0) {
        return this.$errorMsg('当前已选择商品，不可搜索');
      }
      this.table_currentPage = 1;
      this.getGoodsList();
    },

    // 获取商品列表
    getGoodsList() {
      getGoodsList({
        pageNum: this.table_currentPage,
        pageSize: this.table_pageSize,
        keyword: this.keyword,
        categoryId: this.classifyCurrent,
      }).then(res => {
        let oldGoodsList = this.goodsList;
        let newGoodsList = res.data.records;
        for(let i = 0; i < oldGoodsList.length; i++) {
          let oldItem = oldGoodsList[i]
          for(let j = 0; j < newGoodsList.length; j++) {
            let newItem = newGoodsList[j]
            if(newItem.goodsId === oldItem.goodsId){
              newGoodsList[j].selected = true;
              break;
            }
          }
        }
        this.table_dataList = newGoodsList;
        this.table_listTotal = res.data.total;
        this.table_listLoading = false;
      })
    },

    // 查询重复值并禁选
    checkboxSelect (row, rowIndex) {
      if (row.selected) {
        return false // 禁用
      }else{
        return true // 不禁用
      }
    },

    // 更改列表当前页
    handleTableCurrentChange(val) {
      if(this.table_chooseGoods.length > 0) {
        return this.$errorMsg('当前已选择商品，不可切换分页');
      }
      this.table_currentPage = val;
      this.getGoodsList();
    },

    // table点击选择商品
    handleChooseGoods(val) {
      this.table_chooseGoods = val;
    },

    // 打开 选择商品
    addGoods() {
      this.addGoodsVisible = true;
      this.getClassifyList();
    },

    // 取消 选择商品
    cancelAddGoods(){
      this.addGoodsVisible = false;
    },

    // 提交 选择商品
    submitAddGoods() {
      let oldGoodsList = this.goodsList;
      let newGoodsList = this.table_chooseGoods;
      this.goodsList = oldGoodsList.concat(newGoodsList);
      this.addGoodsVisible = false;
    },

    // 删除商品
    deleteGoods(index) {
      this.goodsList.splice(index, 1);
    },

    // 打开 选择分类
    addClassify() {
      this.addClassifyVisible = true;
      this.getClassifyList();
    },

    // 取消 选择分类
    cancelAddClassify(){
      this.addClassifyVisible = false;
    },

    // 提交 选择分类
    submitAddClassify() {
      if(this.$refs.tree.getCheckedNodes().length <= 0) {
        return this.$errorMsg('请选择分类');
      }
      let checkeds = this.$refs.tree.getCheckedNodes();
      let ids = [];
      checkeds.forEach(item => {
        if(item.level === 2) {
          ids.push(item.categoryId);
        }
      })
      getMoreGoodsList({ categoryIds: ids.join(',')}).then(res => {
        let oldGoodsList = this.goodsList;
        let newGoodsList = res.data;
        let allGoodsList = oldGoodsList.concat(newGoodsList);
        let showGoodsList = [];
        let obj = {};
        for(var i =0; i<allGoodsList.length; i++){
            if(!obj[allGoodsList[i].goodsId]){
              showGoodsList.push(allGoodsList[i]);
              obj[allGoodsList[i].goodsId] = true;
            }
        }
        this.goodsList = showGoodsList;
        this.addClassifyVisible = false;
      })
    },

    submitForm() {
      this.$refs.mainForm.validate((valid) => {
        if (valid) {
          if(this.goodsList.length <= 0) {
            return this.$errorMsg('请选择商品');
          }

          let goodsIds = [];
          this.goodsList.forEach(item => {
            goodsIds.push(item.goodsId);
          })

          this.formLoading = true;

          let params = {
            type: 2,
            name: this.mainForm.name,
            logo: this.mainForm.logoUrl,
            logoStartTime: this.mainForm.showDate ? this.mainForm.showDate[0] + ' 00:00:00' : '',
            logoEndTime: this.mainForm.showDate ? this.mainForm.showDate[1] + ' 23:59:59' : '',
            goodsIds: goodsIds
          }
          params = this.$deleteEmptyObj(params);

          if(this.isEdit) {
            params.commonTemplateId = this.editId;
            editModule(params).then(res => {
              this.formLoading = false;
              this.$successMsg('编辑成功');
              setTimeout(()=>{
                this.goBack();
              }, 1000)
            }).catch(err => {
              this.formLoading = false;
            })
          } else {
            addModule(params).then(res => {
              this.formLoading = false;
              this.$successMsg('新增成功');
              setTimeout(()=>{
                this.goBack();
              }, 1000)
            }).catch(err => {
              this.formLoading = false;
            })
          }

        }
      })
    },

    goBack() {
      this.$router.go(-1);
      // this.$store.dispatch("tagsView/delView", this.$route);
    },

    // 水印logo - 上传成功
    uploadSuccess7(res, file) {
      this.mainForm.logoUrl = res.data.url;
    },

    // 水印logo - 上传前
    beforeUpload7(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ['jpg', 'jpeg', 'png'];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$errorMsg('只支持上传jpg/png文件!');
        return false;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
  .dialog-container {
    .left {
      width: 140px;
      height: 350px;
      overflow-y: scroll;
      .group {
        margin-top: 10px;
      }
      .child {
        margin-top: 5px;
        .item {
          padding-left: 18px;
        }
      }
      .item {
        cursor: pointer;
        line-height: 24px;
      }
    }
    .right {
      width: calc(100% - 140px);
      height: 350px;
      box-sizing: border-box;
      padding-left: 20px;
    }
  }

  .classify-list {
    height: 50vh;
    overflow-y: scroll;
  }
</style>