<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"  label-width="68px">
      <el-form-item label="店铺名称 " prop="shopIds">
        <el-select v-model="queryParams.shopIds" placeholder="请选择店铺" clearable style="width:230px">
          <el-option
            v-for="item in shopList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="城市">        
        <el-cascader :options="provinceList" :show-all-levels="false" v-model="province" clearable></el-cascader>        
      </el-form-item> 
      <el-form-item label="状态">
        <el-select v-model="queryParams.state" placeholder="请选择" clearable @keyup.enter.native="handleQuery">
          <el-option label="在线" value="0"/>
          <el-option label="已下线" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item label="轮播位置">
        <el-select v-model="queryParams.target" placeholder="请选择" clearable @keyup.enter.native="handleQuery">
          <el-option label="菜单页顶部" value="1"/>
          <el-option label="我的页banner" value="2"/>
        </el-select>
      </el-form-item>
       <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" v-hasPermi="['banner:applet:query']">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['banner:applet:add']">新增</el-button>
      </el-col>      
    </el-row>

    <el-table v-loading="loading" :data="orderScreenList">    
      <el-table-column label="图片" align="center" >
        <template slot-scope="scope">              
           <div class="image-tmp">
            <el-image style="width: 100px; height: 100px"  :src="scope.row.image" :preview-src-list="getPicsBigList(scope.row.image)">
              <div slot="error" class="image-slot"></div>            
            </el-image>
          </div>    
        </template>
      </el-table-column>
      <el-table-column label="适用范围" align="center" prop="areaLimitDesc"/>
      <el-table-column label="轮播位置" align="center" prop="targetStr"/>
      <el-table-column label="轮播顺序" align="center" prop="sort" />
      <el-table-column label="链接地址" align="center" prop="page" />
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <span v-if="scope.row.state == 0">在线</span>
          <span v-if="scope.row.state == 1">已下线</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-show="scope.row.state == 1" size="mini" type="text" icon="el-icon-edit" @click="handleStatus(scope.row,'0')"
            v-hasPermi="['banner:applet:up']">上线</el-button>
          <el-button v-show="scope.row.state == 0" size="mini" type="text" icon="el-icon-edit" @click="handleStatus(scope.row,'1')"
            v-hasPermi="['banner:applet:down']">下线</el-button> 
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)"
            v-hasPermi="['banner:applet:update']">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['banner:applet:del']">删除</el-button>     
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-form-item label="封面图" prop="image">
            <ImageUpload :value="form.image" v-model="form.image" :limit="1" />
          </el-form-item>
        </el-row>       
        <el-row>
          <el-form-item label="链接地址">
            <el-input v-model="form.page"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="小程序页面路径">
            <el-input  disabled></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="轮播位置" prop="target">
            <el-select v-model="form.target" placeholder="请选择" clearable style="width: 300px;" multiple>
              <el-option label="我的页banner" value='2' />
              <el-option label="菜单页顶部" value='1' />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="适用范围" prop="storesRange">
            <el-cascader ref="area" :options="shopAreaTreeList" v-model="storesRange" :props="{ multiple: true  }" clearable collapse-tags placeholder="请选择地区门店"  
                :show-all-levels="false"  style="width: 300px;"/>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="轮播排序">
            <el-input v-model="form.sort" ></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="resetForm('form')">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getBannerList,addBanner,updateBanner,delBanner,upStateBanner} from "@/api/banner/banner";
import {listShop,getShopCity,getShopAreaTree} from "@/api/system/shop";
import piovince from '@/utils/piovince'
import area from '@/utils/area'

export default {
  name: "Class",
  data() {
    var validateImage = (rule, value, callback) => {
      let imageValue=this.form.image; 
      if (imageValue == undefined || imageValue === '') {        
        callback(new Error('请上传封面图'));
      }else {
        callback();
      }
    };
    var validateStoresRange = (rule, value, callback) => {
      let storesRangeValue=this.storesRange; 
      if (storesRangeValue == undefined || storesRangeValue.length==0) {        
        callback(new Error('请选择适用范围'));
      }else {
        callback();
      }
    };
    return {
      shopList:[],
      piovince,
      // 是否显示弹出层
      open: false,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 表格数据
      orderScreenList: [],
      pageNum: 1,
      pageSize: 10,
      // 查询参数
      queryParams: {
        type:'1',
        shopIds:'',
        target:'',
        state:null,
        city:null
      },
      title:"",
      form:{
        id:null,
        type:'',
        state:null,
        target:[],
        shopIds:[],
        area:[],
        city:[],
        province:[],
        image:"",
        sort:"",
        page:""
      },
      storesRange:[],
      rules:{
        image:[{ required: true, validator: validateImage, trigger: 'blur' }],
        target: [{required: true, message: "不能为空", trigger: "blur" }],
        storesRange:[{ required: true, validator: validateStoresRange, trigger: 'blur' }],
      },
      shopAreaTreeList:[],
      storesRange:[],
      provinceList:[],
      province:[]
    };
  },
  created() {
    this.getList();
    this.getProvinceList();
    this.getShopList();
  },
  methods: {
    getProvinceList(){      
      let list=[];
      this.provinceList=[];
      getShopCity().then((response) => {
        if(response.code==200){
          list=response.data;
          let piovinceList=this.piovince;
          for(let i=0;i<piovinceList.length;i++){
            if(piovinceList[i].children.length>0){            
              let childrenList=piovinceList[i].children;
              let obj={};
              let tag=false;
              obj.value=piovinceList[i].value;
              obj.label=piovinceList[i].label;             
              let children=[];  
              for(let j=0;j<childrenList.length;j++){
                if(list.indexOf(childrenList[j].value)>-1){                                  
                  children.push({"value":childrenList[j].value,"label":childrenList[j].name});   
                    tag=true;          
                }
              }
              obj.children=children; 
              if(tag){
                this.provinceList.push(obj);    
              }                 
            }                 
          } 
        }
      });
    },

    getPicsBigList(str){
      let list=[];      
      list.push(str)
      return list;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pageNum = 1;
      this.queryParams.city=this.province[1];
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.shopIds="";
      this.queryParams.target=null;
      this.queryParams.state=null;
      this.queryParams.city=null;
      this.province=[];
      this.handleQuery();
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getBannerList(this.pageNum,this.pageSize,this.queryParams).then((response) => {
        if(response.code==200){
          this.orderScreenList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      });
    },
    handleAdd(){
      this.open=true;
      this.title="新增轮播图";
      this.reset();
      this.getShopAreaTree(); 
    },
    reset(){
      this.form.id=null;
      this.form.image="";
      this.form.page="";
      this.form.target=[];
      this.storesRange=[];
      this.form.sort="";
      this.form.shopIds=[],
      this.form.area=[],
      this.form.city=[],
      this.form.province=[]
    },
    handleEdit(row){     
      this.open=true;
      this.title="修改轮播图";
      let obj=Object.assign({},row);
      this.form=obj;
      this.form.target=obj.target;
      let list=this.getMap();
      getShopAreaTree().then((response) => {
        if(response.code==200){
          let treeList=response.data;   
          //填充省市区的label值
          for(let i=0;i<treeList.length;i++){
            treeList[i].label=list.get(treeList[i].value);
            if(treeList[i].children.length>0){
              let firChildrenList=treeList[i].children;
              for(let j=0;j<firChildrenList.length;j++){
                firChildrenList[j].label=list.get(firChildrenList[j].value);
                firChildrenList[j].parentObj = treeList[i];

                if(firChildrenList[j].children.length>0){
                  let childrenList=firChildrenList[j].children;
                  for(let s=0;s<childrenList.length;s++){
                    childrenList[s].label=list.get(childrenList[s].value);
                    childrenList[s].parentObj=firChildrenList[j];

                    if(childrenList[s].children){
                      for(let k=0;k<childrenList[s].children.length;k++){
                        childrenList[s].children[k].parentObj = childrenList[s];
                      }
                    }

                  }
                }
              }
            }
          }
          this.shopAreaTreeList=[{value:"0",label:"全国通用"},{value:"1",label:"限定区域",children:treeList}]
          //省市区门店      
          area.getList(this.shopAreaTreeList);
          let ps_ary = area.buildPS(row);
          this.storesRange = ps_ary;
        }
      });
    },
    
    submitForm(){
      var regular=/(^[+]{0,1}([1-9]+)$)/; //自然数
      if(this.form.sort!=""){
        if(!regular.test(this.form.sort)){   
          this.$message.error('轮播排序属性值只能输入自然数!');  
          return; 
        }
      }
      this.form.type="1"
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if(this.storesRange.length>0){
            let proList=[];
            let shopIdList=[];
            let areaIdList=[];
            let cityIdList=[];
            if(this.storesRange[0][0]==0){
              proList.push(0);
            }else{
              let areaNode=this.$refs["area"].getCheckedNodes();
              areaNode=areaNode.filter(item => !(item.parent && item.parent.checked));               
              for(let j=0;j<areaNode.length;j++){
                if(areaNode[j].level==5){
                  shopIdList.push(areaNode[j].value)
                }else if(areaNode[j].level==4){
                  areaIdList.push(areaNode[j].value);
                }else if(areaNode[j].level==3){
                  cityIdList.push(areaNode[j].value);
                }else if(areaNode[j].level==2){
                  proList.push(areaNode[j].value);
                }else if(areaNode[j].level==1){
                   proList.push(0);
                } 
              } 
            }
            this.form.shopIds=shopIdList;
            this.form.area=areaIdList; 
            this.form.city=cityIdList;
            this.form.province=proList;         
          }
          if(this.form.id!=null){
            updateBanner(this.form).then((response) => {
              if(response.code==200){
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          }else{
            this.form.state=0
            addBanner(this.form).then((response) => {
              if(response.code==200){
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }          
        }
      })
    },
    resetForm(){
      this.open=false;
      this.reset();
    },
    handleStatus(row,tag){
      upStateBanner(row.id,tag).then((response) => {
        if(response.code==200){
          if(tag==0){
            this.$modal.msgSuccess("上线成功");            
          }else if(tag==1){
            this.$modal.msgSuccess("下线成功");
          }
          this.getList();
        }
      });
    },
    handleDelete(row){
      this.$modal
        .confirm('是否确认删除该轮播图?')
        .then(function () {
          return delBanner(row.id);
        })
        .then((response) => {  
          if(response.code==200){
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }         
        }).catch(() => { });     
    },
    //获取省市区门店
    getShopAreaTree(){
      let list=this.getMap();
      getShopAreaTree().then((response) => {
        if(response.code==200){
          let treeList=response.data;    
          console.log("treeList     ",treeList);
          //填充省市区的label值
          for(let i=0;i<treeList.length;i++){
            treeList[i].label=list.get(treeList[i].value);
            if(treeList[i].children.length>0){
              let firChildrenList=treeList[i].children;
              for(let j=0;j<firChildrenList.length;j++){
                firChildrenList[j].label=list.get(firChildrenList[j].value);
                firChildrenList[j].parentObj = treeList[i];

                if(firChildrenList[j].children.length>0){
                  let childrenList=firChildrenList[j].children;
                  for(let s=0;s<childrenList.length;s++){
                    childrenList[s].label=list.get(childrenList[s].value);
                    childrenList[s].parentObj=firChildrenList[j];

                    if(childrenList[s].children){
                      for(let k=0;k<childrenList[s].children.length;k++){
                        childrenList[s].children[k].parentObj = childrenList[s];
                      }
                    }

                  }
                }
              }
            }
          }
          this.shopAreaTreeList=[{value:"0",label:"全国通用"},{value:"1",label:"限定区域",children:treeList}]
        }
      });
    },
    //把省市区封装成map集合
    getMap(){
      let list=new Map();
      let piovinceList=this.piovince;      
      for(let i=0;i<piovinceList.length;i++){
        list.set(piovinceList[i].value,piovinceList[i].label);
        if(piovinceList[i].children.length>0){
          let firstList=piovinceList[i].children;
          for(let j=0;j<firstList.length;j++){
            list.set(firstList[j].value,firstList[j].label);
            if(firstList[j].children.length>0){
              let twoList=firstList[j].children;
              for(let t=0;t<twoList.length;t++){
                list.set(twoList[t].value,twoList[t].label);
              }
            }
          }
        }
      }
      return list;
    },
    /** 店铺列表 */
    getShopList() {
      listShop({pageNum:1,pageSize:10000}).then(response => {
        if(response.code=="200"){
          this.shopList=[];
          if(response.rows.length>0){
            for(let i=0;i<response.rows.length;i++){              
              this.shopList.push({value:response.rows[i].id,label: response.rows[i].name},)
            }
          }
        }
      });
    } 


  },
};
</script>
