<template>
  <div>
    <i-page-header class="product_tabs" title="文章板块">
    </i-page-header>
    <Card :bordered="false" dis-hover class="ivu-mt">
	  <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="action">
         <a @click="tapEdit(row.id)">编辑</a>
          <Divider type="vertical"/>
          <a @click="tapDel(row)">删除</a>
        </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>

      <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 {
		SystemGetArtList,
		SystemDelArt
	} from "../../../api/system/adver";
    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: 'id',
					    key: 'id',
					    minWidth: 50
					},
                    {
                        title: '标题',
                        key: 'title',
                        minWidth: 150
                    },
                    {
                        title: '发布时间',
                        key: 'create_time',
                        minWidth: 150
                    },
                    {
                        title: '操作',
                        key: 'action',
                        slot: 'action',
                        fixed: 'right',
                        minWidth: 120
                    }
                ],
                loading: true,
                tableData: [],
                page : {
                    count : 0,//一共多少数量
                    pageSize : 10,//每一页码数量
                    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,
                //     pageSize : this.headeAr[this.headrIndex].children[this.headrIndex2].id
                // };
				let data = {
					page: this.page.page,
					pageSize: this.page.pageSize,
					title: this.formValidate.title
				}
                SystemGetArtList(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.count;
                        } 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});
				this.$router.push('/system/article/detail')
            },
            /**
             * 修改分页
             */
            tapEdit:function(id){
                this.$router.push('/system/article/detail?id=' + id)
            },
            /**
             * 切换广告
             */
            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, "删除数据中...");
                    SystemDelArt({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>
