<template>
  <div class="app-container">
    <div class="operation">
      <el-button v-if="isRoleEdit" class="success" style="float: left;margin-right:10px;" @click="form_add">添加</el-button>

      <!-- <el-button v-if="isRoleEdit" class="import" style="float: right;" @click="form_inport">导入</el-button>
      <el-dropdown style="float: right;margin-right: 10px;">
        <el-button class="export">导出</el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="form_export(1)">导出模板</el-dropdown-item>
          <el-dropdown-item @click.native="form_export(2)">导出数据</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown> -->
    </div>

    <div class="search">
      <!-- <el-input v-model="table.getdataListParm.parammaps.cname" placeholder="产品类别" style="width: 180px;" class="filter-item" clearable /> -->
      <tree-select
            v-model="table.getdataListParm.parammaps.cname"
            class="typeSelect"
            :height="300"
            :width="250"
            clearable
            :data="parentDept"
            :placeholder="placeholder"
            style="display: inline-block;"
            :default-props="defaultProps"
            :node-key="nodeKey"
            :checked-keys="defaultCheckedKeys"
            @popoverHide="popoverHideSelect"
            :disabled="false"
          />

      <el-button class="successBorder" style="margin-left: 20px;" @click="form_search">查询</el-button>
      <el-button class="successBorder" @click="form_clear">重置</el-button>
    </div>

    <div class="table">
      <el-table v-loading="table.listLoading" element-loading-text="给我一点时间"
        row-key="id"
      :data="table.list" border fit highlight-current-row style="width: 100%;" :row-style="rowStyle"
      :cell-style="cellStyle" class="elTable table-fixed"
      :tree-props="{ children: 'children'}" >
        <!-- <el-table-column type="selection" align="center" width="50" /> -->
        <!-- <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="产品类别" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.cname }}</span>
          </template>
        </el-table-column>

        <el-table-column label="产品编码" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.code }}</span>
          </template>
        </el-table-column>

        <el-table-column label="备注" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="顺序" width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column label="启用" min-width="80px" header-align="center" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="change_enable(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <!-- <el-button v-if="isRoleEdit" class="miniSuccess" @click="form_edit(row)">编辑</el-button>
            <el-button v-if="isRoleEdit" class="miniDanger" @click="form_delete(row)">删除</el-button> -->

            <el-button class="miniSuccess" @click="form_edit(row)">编辑</el-button>
            <el-button class="miniDanger" @click="form_delete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <pagination v-show="table.total>=0" :total="table.total" :page.sync="table.getdataListParm.offset" :limit.sync="table.getdataListParm.pagecount" @pagination="get_table_data" /> -->
    </div>

    <!-- 新增/编辑 -->
    <el-dialog :title="textMap[create.dialogStatus]" :visible.sync="create.dialogFormVisible" :close-on-click-modal="false" width="40%">
      <div class="app-add">
        <el-form ref="temp" :rules="create.rules" :model="create.temp" label-position="right" label-width="150px" style="width: 80%;margin:0 auto 50px">

          <el-form-item label="产品类别:" prop="cname" class="filter-item">
            <el-input ref="cname" v-model="create.temp.cname"  />
          </el-form-item>

          <el-form-item label="上级分类"  class="filter-item" style="width: 430px;" prop="pid">
              <tree-select
                class="typeSelect"
                :height="300"
                :width="400"
                size="small"
                clearable
                :data="parentDept"
                :placeholder="placeholder"
                style="display:inline-block;"
                :default-props="defaultProps"
                :node-key="nodeKey"
                :checked-keys="defaultCheckedKeys"
                @popoverHide="popoverHide"
                :disabled="disabled"
              />
            </el-form-item>

            <el-form-item label="产品编码" v-if="create.dialogStatus==='create'" class="filter-item"  prop="code">
              <el-input v-model="create.temp.code" placeholder="请输入编码">
                <template slot="prepend">{{ create.temp.ccode }}</template>
              </el-input>
            </el-form-item>

            <el-form-item label="产品编码" v-if="create.dialogStatus==='update'" class="filter-item"  prop="code">
              <el-input v-model="create.temp.code" placeholder="请输入编码">
              </el-input>
            </el-form-item>

          <el-form-item label="备注:" class="filter-item"  prop="remark">
            <el-input ref="remark" v-model="create.temp.remark" />
          </el-form-item>

          <el-form-item label="顺序:" class="filter-item"  prop="sort">
            <el-input ref="sort" v-model="create.temp.sort" />
          </el-form-item>
          <el-form-item label="启用" class="filter-item"  prop="enable">
            <el-switch ref="enable" v-model="create.temp.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose" @click="create.dialogFormVisible = false;defaultCheckedKeys = [];get_table_data()">关闭</el-button>
          <el-button v-if="create.dialogStatus==='create' || create.dialogStatus==='update'" class="success" @click="create.dialogStatus==='create'?add_dialog_save():form_edit_save()">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { GetDataByName, PostDataByName, failproccess, ExecDataByConfig, GetDataByNames, checkButtons, calculativeWidth ,transData} from '@/api/common'
import { isIntegerZero } from '@/utils/validate'
import TreeSelect from '@/components/TreeSelect'; // 确保路径正确
import Cookies from 'js-cookie'
import { parseTime } from '@/utils/index.js'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'
export default {
  name: 'ProductClass',
  components: { Pagination,TreeSelect },


  data() {
    return {

      isRoleEdit: [],
      nodeKey: 'id', // 节点的唯一标识字段
      disabled: false, // 是否禁用
      placeholder: '请选择上级分类',
      defaultProps: {
        children: 'children',
        label: 'cname', // 根据实际字段名调整
      },
      defaultCheckedKeys: [], // 默认选中的节点
      defaultCheckedSelect:[],
      parentDept: [], // 树形数据
      //表格请求参数~
      table: {
        getdataListParm: {
          name: 'getCategory',
          returntype: 'Map',
          parammaps: {
            cname: '',
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        temp: {}
      },
      getdataListAllParm: {
          name: 'getCategory',
          returntype: 'Map',
          parammaps: {
            cname: '',
          }
        },
      // 新增/编辑
      create: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {
          cname: '',
          ccode:'',
          code:'',
          remark: '',
          sort: '',
          enable: 1
        },
        rules: {
          cname: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          // sort: [{ validator: isIntegerZero, trigger: 'blur' }],
          code :[{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          pid :[{ type: 'number', required: true, message: '必填', trigger: 'blur' }]
        },
      },
      textMap: {
        create: '添加',
        update: '编辑'
      },

      requestParam: {},

      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' }
    }
  },

  created() {
    this.get_table_data()
    this.get_table_data_all()
    // this.get_auto_buttons()
  },

  methods: {

    popoverHide(checkedIds, checkedData) {
      console.log(checkedIds, checkedData);
      // this.create.temp.ccode = checkedData.code;
      this.$set(this.create.temp, 'ccode', checkedData.code);
      if (this.create.dialogStatus === 'update'){
        this.$set(this.create.temp, 'code', checkedData.code);
      }
      // create.temp.code
      this.create.temp.pid = checkedData.id;
    },

    popoverHideSelect(checkedIds, checkedData) {
      if (checkedData == null) {
        this.table.getdataListParm.parammaps.pid = '';
      }else{
        this.table.getdataListParm.parammaps.pid = checkedData.id;
      }

      // this.table.getdataListParm.cname = cname
      console.log(checkedIds, checkedData);
    },
    //获取按钮权限
    get_auto_buttons() {
      const Edit = 'DungScores'
      const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)
      this.isRoleEdit = isRoleEdit
    },

    //加载表格
    get_table_data() {
      // this.defaultCheckedKeys = [];
      this.table.listLoading = true;
      GetDataByName(this.table.getdataListParm).then(response => {
        if (response.data.list !== null) {
          for (var i = 0; i < response.data.list.length; i++) {
            response.data.list[i].enable = parseInt(response.data.list[i].enable)
          }
          // this.table.list = re sponse.data.list
          this.table.list = transData(response.data.list, 'id', 'pid', 'children');
          // this.table.pageNum = response.data.pageNum
          // this.table.pageSize = response.data.pageSize
          // this.table.total = response.data.total
        } else {
          this.table.list = [];

        }
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    get_table_data_all() {
      GetDataByName(this.getdataListAllParm).then(response => {
        if (response.data.list !== null) {
          for (var i = 0; i < response.data.list.length; i++) {
            response.data.list[i].enable = parseInt(response.data.list[i].enable)
          }
          this.parentDept  = transData(response.data.list, 'id', 'pid', 'children');
        } else {

          this.parentDept = [];
        }
      })
    },
    form_search() {
      console.log('点击了查询')

      this.table.getdataListParm.offset = 1
      this.get_table_data()
    },
    form_clear() {
      console.log('点击了重置')
      this.table.getdataListParm.parammaps.cname = ''
      this.table.getdataListParm.offset = 1
      this.get_table_data()
    },

    // 添加
    form_reset() {
      this.create.temp = { cname: '', remark: '', sort: '', enable: 1 }
    },


    //添加
    form_add() {
      console.log('点击了新增')
      this.form_reset()
      this.create.dialogStatus = 'create'
      this.create.temp.sort = 0
      this.create.dialogFormVisible = true
    },
    //添加保存
    add_dialog_save() {
      console.log('点击了新增保存')
      this.create.temp.code = this.create.temp.ccode + '.'+ this.create.temp.code
      this.$refs['temp'].validate(valid => {
        if (valid) {
          //验证名字是否存在
          this.requestParam.name = 'checkCategoryByName'
          this.requestParam.parammaps = this.create.temp
          GetDataByName(this.requestParam).then(response => {
            console.log('验证名字是否存在发送参数', this.requestParam)
            if (response.data.list[0].num == 0) {
              //新增保存
              this.requestParam.name = 'insertCategory'
              this.requestParam.parammaps = this.create.temp
              PostDataByName(this.requestParam).then(response => {
                console.log('新增保存发送参数', this.requestParam)
                if (response.msg !== 'fail') {
                  this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
                  this.create.dialogFormVisible = false
                  this.get_table_data()
                } else {
                  this.$notify({ title: '失败', message: '保存失败', type: 'error', duration: 2000 })
                }
              })
            } else {
              this.$notify({ title: '失败', message: '产品类别已存在', type: 'error', duration: 2000 })
            }
          })

        }
      })
    },


    // 编辑
    form_edit(row) {
      console.log('点击了编辑', row)
      row.barid = String(row.barid)
      this.defaultCheckedKeys = [row.pid]
      this.create.temp = Object.assign({}, row)
      this.create.temp.id = row.id
      this.create.dialogStatus = 'update'
      this.create.temp.sort = 0
      this.create.dialogFormVisible = true
    },

    // 编辑保存
    form_edit_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          this.requestParam.name = 'updateCategory'
          this.requestParam.parammaps = this.create.temp
          PostDataByName(this.requestParam).then(response => {
            console.log('编辑保存发送参数', this.requestParam)
            if (response.msg !== 'fail') {
              this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
              this.create.dialogFormVisible = false
              this.get_table_data()
            } else {
              this.$notify({ title: '失败', message: '保存失败', type: 'error', duration: 2000 })
            }
          })
        }
      })
    },

    // 表格中的启用
    change_enable(index, row) {
      this.requestParam.name = 'updateCategory'
      this.requestParam.parammaps = {
        id: row.id,
        cname: row.cname,
        remark: row.remark,
        sort: row.sort,
        enable: row.enable
      }


      PostDataByName(this.requestParam).then(response => {
        console.log('表格中的启用发送参数', this.requestParam)
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
          this.create.dialogFormVisible = false
          this.get_table_data()
        } else {
          this.$notify({ title: '失败', message: '保存失败', type: 'error', duration: 2000 })
        }
      })


    },

    // 删除
    form_delete(row) {
      MessageBox.confirm('是否确认删除此信息?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        this.requestParam.name = 'delCategory'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.id = row.id
        PostDataByName(this.requestParam).then(response => {
          if (response.msg === 'fail') {
            this.$notify({ title: '删除失败', message: response.data, type: 'warning', duration: 2000 })
          } else {
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
            this.get_table_data()
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },


    // 导出
    form_export(item) {
      if (item == 1) {
        console.log('点击了导出模板')
      } else {
        console.log('点击了导出数据')
      }
    },

    // 导入
    form_inport() {
      console.log('点击了导入')
    }

  }
}
</script>
<style lang="scss" scoped>
.search {
  padding-top: 10px;
  clear: both;
}
.table {
  margin-top: 10px;
}

.filter-item .el-input__inner {
    width: 422px;
}


</style>


