<template>
  <div class="app-container">
    <el-card style="margin-top: 20px;">
        <!-- 查询类别 -->
      <el-form :inline="true" :model="queryParams">
            <el-form-item label="分类名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入分类名称" clearable  @keyup.enter.native="handleQuery"></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="queryParams.status" placeholder="请选择商品状态" clearable >
                    <el-option
                    v-for="dict in dict.type.zhzt"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"/>
                </el-select>
            </el-form-item>
<!--            <el-form-item>-->
<!--                <el-button type="primary" icon="el-icon-search" @click="onQuery">搜索</el-button>-->
<!--                <el-button @click="resetForm" icon="el-icon-refresh" >重置</el-button>-->
<!--            </el-form-item>-->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 15px;">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleAdd"
      >添加分类</el-button>
<!--          <div class="tTop">分类列表-->
<!--              <el-button  type="primary" @click="insertGoods" >添加分类</el-button>-->
<!--          </div>-->
      <!-- default-expand-all二级菜单默认展开 -->
      <!-- 分类列表 -->
      <el-table ref="tables" v-loading="loading" :data="list" row-key="id"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                @selection-change="handleSelectionChange" :default-sort="defaultSort"
                @sort-change="handleSortChange">
        <el-table-column type="index" width="80" align="center" label="序号"/>
        <el-table-column label="分类名称" align="center" prop="name"/>
        <el-table-column label="商品编号" align="center" prop="code"/>
        <el-table-column label="排序" align="center" prop="sorted" />
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.zhzt" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createBy">
          <template slot-scope="scope">
            <span>{{ getName(scope.row.createBy) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed='right'>
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

<!--      <el-table-->
<!--          :data="list"-->
<!--          style="width: 100%;margin-bottom: 20px;"-->
<!--          row-key="id"-->
<!--          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">-->
<!--          &lt;!&ndash; <el-table-column-->
<!--          prop="id"-->
<!--          label="序号"-->
<!--          width="180">-->
<!--          </el-table-column> &ndash;&gt;-->
<!--        <el-table-column label="ID" prop="id" align="center" width="60"/>-->
<!--          <el-table-column prop="categoryName" align="center" label="分类名称" width="180" />-->
<!--          <el-table-column prop="sorted" align="center" label="排序"/>-->
<!--          <el-table-column prop="status" align="center" label="状态" width="180">-->
<!--              <template slot-scope="scope">-->
<!--                  <dict-tag :options="dict.type.zhzt" :value="scope.row.status"/>-->
<!--              </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column prop="createTime" align="center" label="创建时间" width="180" />-->
<!--          <el-table-column prop="createBy" align="center" label="创建人" width="180" />-->
<!--          <el-table-column label="操作" align="center" width="180">-->
<!--              <template slot-scope="scope">-->
<!--                  <el-button type="primary" @click="editeCategory(scope.row)" size="mini">编辑</el-button>-->
<!--                  <el-button type="danger" @click="delCategory(scope.row.id)" size="mini">删除</el-button>-->
<!--              </template>-->
<!--          </el-table-column>-->
<!--      </el-table>-->

    </el-card>

    <!-- 添加类别对话框 -->
    <el-dialog :title="title" :visible.sync="open" class="roll-dialog"
               :close-on-click-modal="false" append-to-body width="500px">
        <el-form :model="form" :inline="true" :rules="rules" ref="form" >
            <el-form-item label="上级分类" >
                <el-select v-model="form.pid" placeholder="请选择上级分类">
                  <el-option label="无上级" :value="0">无上级</el-option>
                  <el-option
                    v-for="item in goodsOptions"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="分类名称" prop="name" style="margin-left: -8px;">
                <el-input v-model="form.name" style="width: 300px;"></el-input>
            </el-form-item>
            <el-form-item label="排序规则">
                <el-input-number v-model="form.sorted" @change="handleChange" :min="0" :max="10" style="width: 300px;"></el-input-number>
            </el-form-item>
            <el-form-item >
                <el-radio-group v-model="form.status">
                <el-radio  v-for="dict in dict.type.zhzt"  :label="dict.value">{{ dict.label }}</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

      <!-- 修改类别对话框 -->
<!--      <el-dialog title="修改分类"  :visible.sync="editDialogFormVisible" width="500px">-->
<!--          <el-form :model="editForm" :inline="true" :rules="rules" ref="editForm" >-->
<!--              <el-form-item label="上级分类" v-if="isShow">-->
<!--                  <el-select v-model="editForm.pid" placeholder="请选择上级分类">-->
<!--                  <el-option-->
<!--                  v-for="item in goodsOptions"-->
<!--                  :label="item.categoryName"-->
<!--                  :value="item.id">-->
<!--                  </el-option>-->
<!--                  </el-select>-->
<!--              </el-form-item>-->
<!--              <el-form-item label="分类名称" prop="categoryName" style="margin-left: -8px;">-->
<!--                  <el-input v-model="editForm.categoryName" style="width: 300px;"></el-input>-->
<!--              </el-form-item>-->
<!--              <el-form-item label="排序规则">-->
<!--                  <el-input-number v-model="editForm.sorted" @change="handleChange" :min="0" :max="10" style="width: 300px;"></el-input-number>-->
<!--              </el-form-item>-->
<!--              <el-form-item >-->
<!--                  <el-radio-group v-model="editForm.status">-->
<!--                  <el-radio   v-for="dict in dict.type.zhzt"  :label="dict.value">{{ dict.label }}</el-radio>-->
<!--                  </el-radio-group>-->
<!--              </el-form-item>-->
<!--          </el-form>-->
<!--          <div slot="footer" class="dialog-footer">-->
<!--              <el-button @click="cancelEdite">取 消</el-button>-->
<!--              <el-button type="primary" @click="saveEdite">确 定</el-button>-->
<!--          </div>-->
<!--      </el-dialog>-->

  </div>
</template>

<script>
import {
  selectTree,
  list,
  insertCvsGoods,
  deleteBYId,
  selectParentById,
  updateCevGood
} from "@/api/convenienceStore/goods.js";
import {delUser, getUser} from "@/api/staff/user/user";
import {getAccount, getAccountList} from "@/api/system/account";
import {addFixingLevel, updateFixingLevel} from "@/api/staff/user/fixinglevel";
export default {
  dicts:['zhzt'],
  data() {
      return {
        creatName:'',
        // 标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 表格数据
        list: [],
        //是否修改一二级菜单
        isShow:false,
        // 默认排序
        defaultSort: {prop: 'updateTime', order: 'descending'},
        //编辑表单
        editForm:{
          pid:'',
          name:'',
          status:'qy',
          sorted:0,
        },
        //父级菜单列表
        goodsOptions:[],
        //查询表单
        goodsQueryForm: {
          name: '',
          status: '',
          pid:"",
          pageNum:'1',
          pageSize:'5'
        },
        // 添加对话框
        dialogFormVisible:false,
        //修改对话框
        editDialogFormVisible:false,
        //对话框表单
        form:{
          pid:'',
          name:'',
          status:'qy',
          sorted:0,
        },
        tableData: [{
          id: '',
          pid:'',
          name: '',
          sorted: '',
          status:'',
          createdTime:'',
          children: []
        }],
        // 查询参数
        queryParams: {
          page: 1,
          pageSize: 10,
          name:'',
          status: '',
        },
        aa:[],
        //校验规则
        rules: {
          name: [
            { required: true, message: '请输入分类名称', trigger: 'blur' },
          ],
        },


      };
  },
  created(){
    this.getList();
    this.getFirstMenu();
  },
  methods: {
    // 表单重置
    reset() {
      this.form = {
        pid:'',
        name:'',
        status:'qy',
        sorted:0,
      }
    },
    // 获取添加者姓名
    getName(id){
      getAccount(id).then(response=>{
        this.creatName = response.data.account.realName
      })
      return this.creatName;
    },
    // 新增按钮操作
    handleAdd() {
      this.reset()
      this.open = true;
      this.title = "新增分类";
    },
    //获取父类
    getFirstMenu(){
        list(this.form).then(response=>{
            this.goodsOptions = response.data
        })
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    handleChange(){
    },
    //提交商品类别
    dooSubmit(){
        this.$refs['form'].validate(valid => {
            if (valid) {
                //新增一级分类
                if(this.form.pid == '' || this.form.pid == undefined ){
                    this.form.pid = 0
                }
                //新增二级
                insertCvsGoods(this.form).then(response=>{
                    if (response.code === 200) {
                       this.rest()
                        this.$message('新增成功');
                    }else{
                        this.$message('新增失败 请联系管理员');
                    }

                })


            }
        })
    },
    rest(){
        this.dialogFormVisible = false
        this.resetForm();
        this.goodsOptions = []
    },
    // 取消提交
    cancelSubmit(){
        this.$refs.form.resetFields();//清空
        this.form.name = ''
        this.form.pid = ''
        this.form.status = ''
        this.form.sorted = 0
        this.dialogFormVisible = false
    },
    // 分页查询
    getList(){
      this.loading = true;
      selectTree(this.queryParams).then(response => {
        if (response.data!=null){
          this.list = response.data.records;
          this.total = response.data.total;
        }else {
          this.list = [];
          this.total = 0;
        }
        this.loading = false;
      });
    },
    // 取消查询
    resetForm(){
        this.goodsQueryForm.name = ''
        this.goodsQueryForm.status = ''
        this.getList()
    },
    // 提交按钮
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.pid==""){
            this.form.pid = 0
          }
          if (this.form.id) {
            updateCevGood(this.form).then(response => {
              if (response.data==1){
                this.$modal.msgSuccess("分类更新成功");
                this.open = false;
                this.getList();
                this.getFirstMenu();
              }else {
                this.$modal.msgError("分类名称已存在，修改失败");
              }

            });
          } else {
            insertCvsGoods(this.form).then(response => {
              if (response.data == -1){
                this.$modal.msgError("分类名称已存在，添加失败");
              }else {
                this.$modal.msgSuccess("分类添加成功");
                this.open = false;
                this.getList();
                this.getFirstMenu();
              }
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      selectParentById(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "编辑分类";
      });
    },
    // 删除按钮操作
    handleDelete(row) {
      const name = row.name
      this.$modal.confirm('确定删除"' + name + '"的分类信息？').then(function() {
        // return deleteMember(row.id);
        return deleteBYId(row.id);
      }).then(() => {
        this.queryParams.page = 1
        this.getList();
        this.getFirstMenu();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    // 排序触发事件
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped>
  .tTop{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  .pageSty{
    display: flex;
    justify-content: center;
    margin-left: 250px;
  }
  .app-container{
    width: 100%;
    height: 100vh;
    background: #f6f8f9;
  }
</style>
