<template>
  <div>
    <i-page-header class="product_tabs" title="广告栏目">
    </i-page-header>
    <Card :bordered="false" dis-hover class="ivu-mt">

      <div class="fx-r fx-bc">
          <el-button-group>
              <el-button v-for="(item,index) in headeAr" :key="index" @click="tapEl1(index)" :type=" headrIndex == index ? 'primary' : '' ">{{item.cate_name}}</el-button>
          </el-button-group>
      </div>

      <div class="fx-r fx-bc" style=" margin-top: 20px;" v-if="headeAr[headrIndex] != null">
        <el-button-group>
          <el-button v-for="(item,index) in headeAr[headrIndex].children" :key="index" @click="tapEl2(index)" :type=" headrIndex2 == index ? 'primary' : '' ">{{item.cate_name}}</el-button>
        </el-button-group>
      </div>
	  
	  <div style="height: 30px;"></div>
	  
	  
      <Form ref="formValidate" :model="formValidate" :label-width="50">
        <Row type="flex"  :gutter="24">
          <Col v-bind="grid">
            <FormItem label="搜索："  label-for="status2">
              <Input search enter-button placeholder="请输入广告名称" v-model="formValidate.title" @on-search="userSearchs"/>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex">
          <Col v-bind="grid">
            <Button type="primary" @click="tapAdd"  icon="md-add">添加新广告</Button>
          </Col>
        </Row>
      </Form>

      <Table :columns="columns1" :data="tableData" class="mt25" no-userFrom-text="暂无数据"
             no-filtered-userFrom-text="暂无筛选结果"  :loading="loading" highlight-row>

        <template slot-scope="{ row, index }" slot="imgs">
          <img v-lazy="row.img" :src="row.img" v-image-preview style="width: 120px;cursor: pointer;"/>
        </template>

        <template slot-scope="{ row, index }" slot="data">
          <div v-for="(item,index) in row.jsonAr" :key="index">
            {{ item.name}}：{{ item[item.code] }}
          </div>
        </template>

        <template slot-scope="{ row, index }" slot="status">
          <el-tag v-if="row.is_show == 1">开启</el-tag>
          <el-tag type="info" v-else>关闭</el-tag>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <a @click="tapEdit(row.id)">编辑</a>
          <Divider type="vertical"/>
          <a @click="tapDel(row)">删除</a>
        </template>

        <template slot-scope="{row,index}" slot="img">
          <el-avatar icon="el-icon-user-solid" :src="row.img"></el-avatar>
        </template>

      </Table>

      <div class="acea-row row-right page">
        <Page :total="page.count" show-elevator show-total @on-change="tapPage"
              :page-size="page.pageSize"/>
      </div>
    </Card>


    <Modal
      v-model="dialogVisible"
      :title="title"
      @on-cancel="editClose">

      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="广告名称" prop="title"
                      :rules="[{ required: true, message: '请输入广告名称'}]">
          <el-input placeholder="请输入广告名称" autocomplete="off" v-model="form.title"></el-input>
        </el-form-item>


        <el-form-item label="广告分类：" prop="page_id"
                      :rules="[{ required: true, message: '请输入选择广告分类'}]"
        >
          <Select v-model="form.page_id"
          @on-change="tapChanggePage"
          >
            <Option v-for="(item,index) in adverPage"   :disabled="item.pid === 0" :value="item.id" :key="item.id">{{ item.html + item.cate_name }}</Option>
          </Select>
        </el-form-item>

        <el-form-item label="广告图" prop="img" :rules="[{ required: true, message: '请上传广告图'}]"  v-if="adverPageOne.type == 1">
          <ui-upload
            :upUrl="upUrl"
            :img ="form.img"
            fileName="广告图"
            :headers="upHeaders"
            :updata="{isz:0,code:'advert'}"
            @onUpload="onUpload"
          ></ui-upload>
        </el-form-item>
        <div v-for="(item,index) in dataAr" :key="index">
          <el-form-item :prop="item.code" :label="item.name">
            <el-input v-model="item[item.code]" :placeholder="'请输入' + item.name" ></el-input>
          </el-form-item>
        </div>



        <el-form-item label="广告内容" prop="text"
                      :rules="[{ required: true, message: '请输入广告内容'}]" v-if="adverPageOne.type == 2">
          <el-input type="textarea" placeholder="请输入广告内容" autocomplete="off" v-model="form.text"></el-input>
        </el-form-item>

        <el-form-item label="排序">
          <el-input  placeholder="排序越高越前面" v-model="form.sort"></el-input>
        </el-form-item>

        <el-form-item label="是否显示" style="margin-bottom: 0;">
          <el-radio-group v-model="form.is_show">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
		
		
		<el-form-item label="广告链接地址" >
		  <el-input placeholder="请输入广告链接地址" autocomplete="off" v-model="form.url"></el-input>
		  <!-- <div>商品详情：/pages/shop/item?id=商品ID</div> -->
		  <!-- <div>活动详情：/pages/promotion/item?id=活动ID</div>
		  <div>动态发布：/pages/user/circle/add</div> -->
		</el-form-item>
		
		

      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="subAdmin">确 定</el-button>
        </span>
    </Modal>

  </div>
</template>

<script>
    import IPageHeader from "@/layouts/system/page-header/index";
    import { mapState, mapActions } from 'vuex';
    import UiUpload from "@/ui/upload/index";
    import Setting from "@/setting";
    import util from "@/libs/util";
    import {
        SystemAdverPage,
        SystemAdverPageTree,
        SystemAdverUpdate,
        SystemAdver,
        SystemAdverInfo, SystemAdverDel
    } from "../../../api/system/adver";
    export default {
        name: "adver_index",
        components: { UiUpload, IPageHeader},
        computed: {
        },
        data() {
            return {
                title:"账号管理",
                dialogVisible:false,
                upHeaders:[],
                upUrl:"",
                grid: {
                    xl: 7,
                    lg: 7,
                    md: 12,
                    sm: 24,
                    xs: 24
                },
                artType     : "all",
                headeAr     : [],
                headrIndex  : 0,
                headrIndex2 : 0,
                adverPage   : [],
                adverPageOne : {},
                columns1: [
                    {
                        title: '标题',
                        key: 'title',
                        minWidth: 150
                    },
                    {
                        title: '广告图片',
                        key: 'img',
                        slot:"imgs",
                        minWidth: 150
                    },
                    {
                        title: '广告类型',
                        key: 'cate_name',
                        minWidth: 180
                    },

                    {
                        title: '链接地址',
                        key: 'url',
                        minWidth: 150
                    },


                    {
                        title: '数据属性',
                        key: 'data',
                        slot:'data',
                        minWidth: 150
                    },

                    {
                        title: '发布时间',
                        key: 'time',
                        minWidth: 150
                    },
                    {
                        title: '排序',
                        key: 'sort',
                        minWidth: 100,
                        fixed: 'right',
                    },
                    {
                        title: '状态',
                        key: 'status',
                        slot:"status",
                        minWidth: 100,
                        fixed: 'right',
                    },
                    {
                        title: '操作',
                        key: 'action',
                        slot: 'action',
                        fixed: 'right',
                        minWidth: 120
                    }
                ],
                loading: true,
                tableData: [],
                page : {
                    count : 0,//一共多少数量
                    pageSize : 0,//每一页码数量
                    page : 1,//当前页码
                },
                formValidate:{title:""},
                form:{
                    title     : "",
                    text      : "",
                    url       : "",
                    img       : "",
                    sort      : 0,
                    is_show   : 1,
                    page_id   : 0
                },
                dataAr    : []
            }
        },
        mounted(){
            this.initView();
        },
        methods: {
            initView : function(){
                var upHeaders = {};
                this.upUrl = Setting.apiBaseURL + "/systemv1/upload/index";
                const token = this.$utils.util.cookies.get('system_token');
                if (token) {
                    upHeaders['SYSTEM-ACC-TOKEN'] = token;
                }
                this.upHeaders = upHeaders;
                this.getAdverPage();
            },


            getAdverPage:function(){
                this.$utils.loading(this, "删除数据中...");
                var PromiseAll = [SystemAdverPageTree(),SystemAdverPage()];
                Promise.all(PromiseAll)
                    .then(res=>{
                        this.$utils.loadingClose();
                        this.adverPage = res[0].data;
                        this.headeAr = res[1].data;
                        this.getData();
                    })
                    .catch(err=>{
                        console.log(err);
                        this.$utils.loadingClose();
                        this.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
                    });
            },

            /**
             * 获取数据
             */
            getData:function () {
                if (this.headeAr[this.headrIndex] == null ||
                    this.headeAr[this.headrIndex].children[this.headrIndex2] == null) {
                    return ;
                }
                var data = {
                    title : this.formValidate.title,
                    page : this.page.page,
                    page_id : this.headeAr[this.headrIndex].children[this.headrIndex2].id
                };
                SystemAdver(data)
                    .then(res=>{
                        this.loading = false;
                        if(res.code == 200) {
                            this.tableData = res.data.list;
                            this.page.pageSize = res.data.pageSize;
                            this.page.count = res.data.pageCount;
                        } else {
                            this.$alert(res.msg);
                        }
                    })
                    .catch(err=>{
                        console.log(err);
                        this.loading = false;
                        this.$utils.loadingClose();
                        this.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
                    });
            },
            userSearchs () {
                this.page.page = 1;
                this.loading = true;
                this.getData();
            },

            tapEl1:function(index){
                this.headrIndex = index;
            },
            tapEl2:function(index){
                this.headrIndex2 = index;
                this.page.page = 1;
                this.loading = true;
                this.getData();
            },

            tapInput:function(ethis,index,code){
              console.log(ethis);
            },
            //关闭
            editClose:function(){
                this.dialogVisible = false;
            },
            /**
             * 添加广告栏目
             */
            tapAdd:function(sassid){
                this.dialogVisible = true;
                if(this.headeAr.length <= 0) {
                    this.$alert('无广告栏目，无法添加');
                }
                var data = this.headeAr[this.headrIndex].children[this.headrIndex2];
                this.dataAr = data.json == '' ? [] : JSON.parse(data.json);
                this.adverPageOne = data;
                this.$refs['form'].resetFields();
                this.form = this.$utils.resetFields(this.form, {page_id:data.id});
            },
            /**
             * 修改分页
             */
            tapEdit:function(id){
                this.$utils.loading(this,"获取数据中...");
                SystemAdverInfo({id:id})
                    .then(res=>{
                        this.$utils.loadingClose();
                        if(res.code == 200) {
                            this.form = res.data;
                            var pageData = null;
                            for(var i in this.adverPage) {
                                if(this.form.page_id == this.adverPage[i].id) {
                                    pageData = this.adverPage[i];
                                }
                            }
                            //循环page
                            if(pageData != null) {
                                var jsonData = pageData.json == '' ? [] : JSON.parse(pageData.json);
                                var json2Data = res.data.data == '' ? [] : JSON.parse(res.data.data);
                                for (var ii in jsonData) {
                                    for (var i in json2Data) {
                                        if (json2Data[i].code == jsonData[ii].code) {
                                            jsonData[ii][jsonData[ii].code] = json2Data[i][jsonData[ii].code];
                                        }
                                    }
                                }
                            }
                            this.adverPageOne =pageData;
                            this.dataAr = jsonData;
                            this.dialogVisible = true;
                            this.title = "修改广告";
                        } else {
                            this.$alert(res.msg);
                        }
                    })
                    .catch(err=>{

                        this.$utils.loadingClose();
                        this.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
                    });
            },
            /**
             * 切换广告
             */
            tapChanggePage:function(id){
              var data = {};
              for(var i in this.adverPage) {
                  if(this.adverPage[i].id == id) {
                      data = this.adverPage[i];
                  }
              }
              var jsonData = data.json == '' ? [] : JSON.parse(data.json);
              this.dataAr = jsonData;
            },
            /**
             * 分页
             */
            tapPage:function(index){
                this.page.page = index;
                this.getData();
            },
            /**
             * 修改数据
             */
            subAdmin:function(){
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        let loading = this.$loading("提交数据中...");
                        var data = {};
                        for(var i in this.form) {
                            data[i] = this.form[i];
                        }
                        data['data'] = JSON.stringify(this.dataAr);
                        SystemAdverUpdate(data)
                            .then(res => {
                                loading.close();
                                if (res.code == 200) {
                                    this.dialogVisible = false;
                                    this.$Message.success("操作成功");
                                    this.getData();
                                } else {
                                    this.$alert(res.msg, '系统提示');
                                }
                            })
                            .catch(err => {
                                loading.close();
                                this.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
                            });
                    }
                });
            },
            /**
             * 上传文件
             * @param res
             */
            onUpload:function (res) {
                if(res.code == -1) {
                    Notice.error({ title : "系统提示", content:res.msg});
                } else {
                    this.form.img = res.data.img;
                }
            },
            // 删除
            tapDel (row) {
                this.$confirm('此操作将永久删除该栏目分类, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$utils.loading(this, "删除数据中...");
                    SystemAdverDel({id: row.id})
                        .then(res => {
                            this.$utils.loadingClose();
                            this.loading = true;
                            if (res.code == 200) {
                                this.getData();
                            } else {
                                this.$alert(res.msg);
                            }
                        })
                        .catch(err => {
                            this.$utils.loadingClose();
                            this.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
                        });
                });
            },
        }
    }
</script>
<style scoped>
  .platform-img{width: 20px;height: 20px;background: #f2f2f2; margin-right: 4px;}
  .platform-img img{ width: 100%;}
</style>
