<template>
  <div class="article-manager">
    <i-page-header title="课程分类"></i-page-header>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Form ref="artFrom" :model="artFrom" :label-width="75">
        <Row type="flex" :gutter="24">
          <!-- <Col v-bind="grid">
            <FormItem label="广告分类：" prop="pid" label-for="pid">
              <Select v-model="artFrom.pid" @on-change="userSearchs" clearable>
                <Option v-for="item in treeSelect" :value="item.id" :key="item.id">{{ item.html + item.cate_name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col v-bind="grid">
            <FormItem label="状态："  label-for="is_show">
              <Select v-model="artFrom.is_show" placeholder="请选择" clearable  @on-change="userSearchs">
                <Option value="1">显示</Option>
                <Option value="0">隐藏</Option>
              </Select>
            </FormItem>
          </Col>
          <Col v-bind="grid">
            <FormItem label="分类名称："  label-for="status2">
              <Input search enter-button placeholder="请输入" v-model="artFrom.cate_name" @on-search="userSearchs"/>
            </FormItem>
          </Col> -->
        </Row>
       <!-- <Row type="flex">
          <Col v-bind="grid">
            <Button type="primary" class="bnt" icon="md-add" @click="tapAdd">添加新分类</Button>
          </Col>
        </Row> -->
      </Form>
      <vxe-table
        class="mt25"
        highlight-hover-row
        :loading="loading"
		 default-expand-all
        header-row-class-name="false"
        :tree-config="{children: 'children',hasChildren:true}"
        :data="tableData">
        <vxe-table-column field="id" title="ID"  tooltip width="80"></vxe-table-column>
        <vxe-table-column field="name" tree-node title="分类名称"  min-width="250" ></vxe-table-column>
		<vxe-table-column field="sort" title="排序"  min-width="250" ></vxe-table-column>
        <vxe-table-column field="date" title="操作" width="250" fixed="right" align="center">
          <template v-slot="{ row, index }">
			  <a @click="tapAddKid(row)">添加子类</a>
			  <Divider type="vertical"/>
            <a @click="tapEdit(row)">编辑</a>
            <Divider type="vertical"/>
            <a @click="del(row,'删除课程分类',index)">删除</a>
          </template>
        </vxe-table-column>
      </vxe-table>
    </Card>
    <Modal
      v-model="dialogVisibleEdit"
      title="修改分类"
      :modal="false"
      @on-cancel="editClose2">
      <el-form ref="editcate" :model="menu" label-width="120px">
        <el-form-item label="分类名称" prop="name"
                      :rules="[{ required: true, message: '请输入分类名称'}]">
          <el-input placeholder="请输入分类名称" autocomplete="off" v-model="menu.name"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort"
                      :rules="[{ required: true, message: '请输入排序'}]">
          <el-input placeholder="请输入排序" autocomplete="off" v-model="menu.sort" type="number"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleEdit = false">取 消</el-button>
          <el-button type="primary" @click="subJson">确 定</el-button>
        </span>
    </Modal>
	<Modal
	  v-model="dialogVisibleAdd"
	  title="添加子分类"
	  :modal="false"
	  @on-cancel="editClose2">
	  <el-form ref="addchildren" :model="addmenu" label-width="120px">
	    <el-form-item label="分类名称" prop="name"
	                  :rules="[{ required: true, message: '请输入分类名称'}]">
	      <el-input placeholder="请输入分类名称" autocomplete="off" v-model="addmenu.name"></el-input>
	    </el-form-item>
	    <el-form-item label="排序" prop="sort"
	                  :rules="[{ required: true, message: '请输入排序'}]">
	      <el-input placeholder="请输入排序" autocomplete="off" v-model="addmenu.sort" type="number"></el-input>
	    </el-form-item>
	  </el-form>
	  <span slot="footer" class="dialog-footer">
	      <el-button @click="dialogVisibleAdd = false">取 消</el-button>
	      <el-button type="primary" @click="addKidCate">确 定</el-button>
	    </span>
	</Modal>
  </div>
</template>

<script>
    import { mapState } from 'vuex';
    import IPageHeader from "../../../layouts/system/page-header/index";
    import Setting from "../../../setting";
    import UiUpload from "../../../ui/upload/index";
    import {SystemAdverPageDel, SystemAdverPageInfo, SystemAdverPage, SystemAdverPageTree,SystemAdverPageUpdate,getCate,editCate,subcateadd,delCate} from "../../../api/system/adver";
    export default {
        name: 'page',
        components: {
            UiUpload,
            IPageHeader
        },
        data () {
            return {
				dialogVisibleAdd:false,//添加子类弹窗
				dialogVisibleEdit: false,//编辑弹窗
                title : "添加广告分类",
                treeSelect: [],
                FromData: null,
                dialogVisible:false,
                dialogVisible2:false,
                grid: {
                    xl: 7,
                    lg: 7,
                    md: 12,
                    sm: 24,
                    xs: 24
                },
                adverType:[
                    {"name":"图片模式",id:1},
                    {"name":"文字模式",id:2},
                ],
                adverJsonType:[
                    {"name":"文本类型","value":"text"},
                    {"name":"图片类型","value":"img"},
                    {"name":"链接类型","value":"url"},
                    {"name":"产品ID","value":"id"},
                ],
                loading: false,
                artFrom: {
                    pid: 0,
                    is_show: '',
                    page: 1,
                    cate_name: ''
                },
                tableData: [],
                menu:{
                    id : 0,
					name: '',
					sort: 0
                },
				addmenu: {
					pid: 0,
					name: '',
					sort: 0
				},
                 menuJsonIndex : -1,
                json:{
                    name:"",
                    code:"",
                    type : ""
                }
            }
        },
        created(){

        },
        mounted () {
            this.goodsCategory();
            this.getList();
        },
        methods: {
			//添加子类
			addKidCate() {
				let that = this
				// subcateadd(that.addmenu).then(res => {
				// 	console.log(res);
				// 	this.$Message.success("添加子分类成功");
				// 	 this.getList();
				// 	 this.dialogVisibleAdd = false;
				// })
				that.$refs.addchildren.validate(val => {
					if(val) {
						subcateadd(that.addmenu).then(res => {
							console.log(res);
							that.$Message.success("添加子分类成功");
							 that.getList();
							 that.dialogVisibleAdd = false;
						})
					}
				})
			},
			//打开添加子类弹出
			tapAddKid(item) {
				this.addmenu.pid = item.id
				this.dialogVisibleAdd = true
			},
            // 商品分类；
            goodsCategory () {
                SystemAdverPageTree().then(res => {
                    this.treeSelect = ([ {'cate_name':'请选择分类','html':"",'id':0} ]).concat(res.data);
                }).catch(res => {
                    this.$Message.error(res.msg);
                })
            },
            // 列表
            getList () {
                this.loading = true;
                this.artFrom.is_show = this.artFrom.is_show || '';
                this.artFrom.pid = this.artFrom.pid || '';
                getCate(this.artFrom)
                    .then(res=>{
                        let data = res.data;
                        this.tableData = data;
                        this.loading = false;
                    })
                    .catch(err=>{
                        this.loading = false;
                        this.$Message.error(res.msg);
                    });
            },
            /**
             * 添加新分类
             */
            tapAdd:function () {
                // this.dialogVisible = true;
                // this.$refs['menu'].resetFields();
                // this.menu = this.$utils.resetFields(this.menu,{type:1,jsonAr:[]});
				this.$router.push('/system/eduction/detail')
            },
            /**
             * 添加自定义分类
             */
            tapAddJson:function(){
                this.dialogVisible2 = true;
                this.$refs['json'].resetFields();
                this.json = this.$utils.resetFields(this.json);
            },
            /**
             * 删除自定义分类
             */
            tapJsonDel:function(index){
                this.menu.jsonAr.splice(index,1);
            },
            /**
             * 修改自定义分类
             */
            tapJsonEdit:function(index){
                this.menuJsonIndex = index;
                this.json = this.menu.jsonAr[index];
                this.dialogVisible2 = true;
            },

            /**
             * 关闭
             */
            editClose:function(){
                this.dialogVisible = false;
            },
            /**
             * 关闭弹出层
             */
            editClose2:function(){
                this.dialogVisibleEdit = false;
            },
            /**
             * 编辑分类
             */
            subJson:function(){
				let that = this
				this.$refs.editcate.validate(val=> {
					if(val) {
						editCate({
							id: that.menu.id,
							name: that.menu.name,
							sort: that.menu.sort
						}).then(res => {
							console.log(res);
							this.$Message.success("修改成功");
							 this.getList();
							 this.dialogVisibleEdit = false;
						})
					}
				})
            },
            /**
             * 修改数据
             */
            subAdmin:function(){
                this.$refs['menu'].validate((valid) => {
                    if (valid) {
                        let loading = this.$loading("提交数据中...");
                        var data = {};
                        for(var i in this.menu) {
                            if(typeof(this.menu[i]) == "object"){
                                data['json'] = JSON.stringify(this.menu[i]);
                            } else {
                                data[i] = this.menu[i];
                            }
                        }
                        SystemAdverPageUpdate(data)
                            .then(res => {
                                loading.close();
                                if (res.code == 200) {
                                    this.dialogVisible = false;
                                    this.$Message.success("操作成功");
                                    this.getList();
                                    this.goodsCategory();
                                } else {
                                    this.$alert(res.msg, '系统提示');
                                }
                            })
                            .catch(err => {
                                loading.close();
                                this.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
                            });
                    }
                });
            },
            // 删除
            del (row, tit, num) {
                this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delCate({id: row.id})
                        .then(res => {
                            this.loading = true;
                            this.getList();
                            // this.goodsCategory();
                            this.$Message.success("删除成功");
                        })
                        .catch(err => {
                            this.$utils.loadingClose();
                            this.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
                        });
                });
            },
            /**
             * 修改分类
             */
            tapEdit:function(item){
				console.log(item);
				let that = this
				that.menu = {id: item.id,name: item.name, sort: item.sort}
				 this.dialogVisibleEdit = true;
                // this.$utils.loading(this,"获取数据中...");
                // SystemAdverPageInfo({id:id})
                //     .then(res=>{
                //         this.$utils.loadingClose();
                //         if(res.code == 200) {
                //             this.menu = res.data;
                //             this.menu.jsonAr = res.data.json == "" ? [] :  JSON.parse(res.data.json);
                //             this.dialogVisible = true;
                //             this.title = "修改广告分类";
                //         } else {
                //             this.$alert(res.msg);
                //         }
                //     })
                //     .catch(err=>{
                //         this.$utils.loadingClose();
                //         this.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
                //     });
            },
            // 表格搜索
            userSearchs () {
                this.artFrom.page = 1;
                this.getList();
            },

            getJsonName:function (type) {
                for (var i in this.adverJsonType){
                    if(type == this.adverJsonType[i].value) {
                        return this.adverJsonType[i].name;
                    }
                }
            }
        }
    }
</script>
<style scoped lang="stylus">
  .treeSel >>>.ivu-select-dropdown-list
    padding 0 10px!important
    box-sizing border-box
  .tabBox_img
    width 36px
    height 36px
    border-radius:4px
    cursor pointer
    img
      width 100%
      height 100%
</style>
