<template>
  <div class="specialAttr">
    <!-- <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">

        <el-select size="small" v-model="textValue" placeholder="请选择">
        <el-option
          v-for="item in text"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>

      <el-select size="small" v-model="ruleValue" placeholder="请选择">
        <el-option
          v-for="item in rule"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>

      <el-input
        v-model="input"
        size="small"
        placeholder="请输入"
        clearable
        style="width: 240px"
      />

      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" size="small" plain>查询</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="small" plain>高级查询</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="small" plain>重置</el-button>
      </el-col>

    </el-row> -->

    <el-card>
      <el-row :gutter="10" class="content">
        <el-col :span="6">
          <el-input
            placeholder="输入关键字进行过滤"
            size="small"
            v-model="filterText">
          </el-input>

          <el-tree
            class="filter-tree"
            :data="data"
            :props="defaultProps"
            @node-click="clickTree"
            :filter-node-method="filterNode"
            ref="tree">
          </el-tree>
        </el-col>
        
        <el-col :span="18">

          <el-row>
            <el-button type="primary" size="small" plain @click="addSpc">新增</el-button>
            <el-button type="primary" size="small" plain @click="deleteSpc">删除</el-button>
          </el-row>

          <el-row>
            <el-table 
              :data="taskList" 
              class="request-table"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column label="排序" align="center" prop="sort" />
              <el-table-column label="属性名称" align="center" prop="attributeName" />
              <el-table-column label="属性编码" align="center" prop="classCode" />
              <el-table-column label="字段类型" align="center" prop="fieldType" />
              <el-table-column label="字段ID值" align="center" prop="dictId" />
              <el-table-column label="字段说明" align="center" prop="fieldDesc" />
              <el-table-column
                fixed="right"
                label="操作"
                align="center"
                width="100">
                <template slot-scope="scope">
                  <el-button @click="edit(scope.row)" type="text" size="small">修改</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>

        </el-col>
      </el-row>
    </el-card>

    <!-- 新增弹窗 -->
    <el-dialog :title="titles" :visible.sync="dialogFormVisible" center>
      <el-form :model="form" :rules="rules" ref="bindForm">
        <el-row>
          <el-col :span="16">
            <el-form-item label="属性名称" prop="attributeName" label-width="120px">
              <el-input v-model="form.attributeName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="属性编码" prop="attributeCode" label-width="120px">
              <el-input v-model="form.attributeCode"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="字段类型" prop="fieldType" label-width="120px">
                  <el-select
                    v-model="form.fieldType"
                    placeholder="字段类型"
                    clearable
                    style="width: 285px"
                  >
                    <el-option
                      v-for="dict in dict.type.template_field_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="字典ID值" prop="dictId" label-width="120px">
              <el-autocomplete
                class="inline-input"
                v-model="form.dictId"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                prefix-icon="el-icon-search"
                style="width: 285px"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="排序" prop="sort" label-width="120px">
              <el-input v-model="form.sort"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="字段说明" prop="fieldDesc" label-width="120px">
              <el-input v-model="form.fieldDesc"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('bindForm')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getTree } from '@/api/classify/basic';
import { add, getDetail, delSpecial, editSpecial } from '@/api/special/basic';
export default {
  name: 'specialAttr',
  dicts: ['template_field_type'],
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data () {
    return{
      textValue: 1,
      text: [{label: '文本字段', value: 1}, {label: '字典字段', value: 2}],
      ruleValue: 1,
      rule:[{label: '包含', value: 1}, {label: '不包含', value: 2}, {label: '等于', value: 3}, {label: '不等于', value: 4}],
      input: '',
      filterText: '',
      data: [],
      defaultProps: {
          children: 'childrens',
          label: 'materialType'
      },
      taskList:[],
      // 判断是否为最末级节点
      isLast: false,
      // 弹框默认隐藏
      dialogFormVisible: false,
      titles: '新增',
      // 表单
      form: {
        attributeName: '',
        attributeCode: '',
        fieldType: '',
        dictId: '',
        sort: '',
        fieldDesc: ''
      },
      rules: {
        // attributeName:[{ required: true, message: '请输入属性名称', trigger: 'blur' }],
        // attributeCode:[{ required: true, message: '请输入属性编码', trigger: 'blur' }],
        // fieldType:[{ required: true, message: '请选择字段类型', trigger: 'change' }],
        // sort:[{ required: true, message: '请输入属性编码', trigger: 'blur' }],
      },
      // 搜索框内容
      restaurants: [],
      // 获取节点的code
      treeData: {
        classCode: ''
      },
      // 表格内选中条目
      arr: [],
    }
  },
  created() {
    this.getTreeData()
  },
  methods: {
    // 获取树形结构
    getTreeData(data) {
      getTree({}).then(res => {
        let {code, rows} = res
        if(code === 200) {
          this.data = rows
        }
      })
    },
    // 获取详情方法
    getDetailData(code) {
      getDetail(code).then(res => {
        if(res.code === 200) {
          this.taskList = res.data
        }
      })
    },
    // 点击树形节点,调用详情接口
    clickTree(data) {
      console.log('树形节点信息：',data)
      // 判断是否为最末级节点
      if (data.childrens.length == 0) {
        this.isLast = true
      } else {
        this.isLast = false
      }
      this.treeData.classCode = data.code
      this.getDetailData(data.code)
    },
    // 新增最末级物料分类的特殊属性
    addSpc() {
      // 如果不是最末级节点则给出提示
      if(this.isLast) {
        this.dialogFormVisible = true
        this.titles = '新增'
        this.$nextTick(() => {
          this.form = {
            attributeName: '',
            attributeCode: '',
            fieldType: '',
            dictId: '',
            sort: '',
            fieldDesc: ''
          }
        })
      } else {
        this.$message({
          message: '请先选中最末级节点',
          type: 'warning'
        });
      }
    },
    // 表单填写提交
    submit(formName) {
      console.log('表单', formName)
      this.$refs[formName].validate((valid) => {
        if(valid) {
          if(this.titles == '新增') { //判断是走新增接口还是修改接口
            let params = {...this.form, ...this.treeData}
            console.log('params', params)
            add(params).then(res => {
              if(res.code === 200) {
                // 关闭弹窗，调用查询接口,清空输入内容
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
                this.getDetailData(this.treeData.classCode)
                this.dialogFormVisible = false
                this.$refs['bindForm'].resetFields();
              }
            })
          } else {
            editSpecial(this.form).then(res => {
              if(res.code === 200) {
                // 关闭弹窗，调用查询接口,清空输入内容
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
                this.getDetailData(this.form.classCode)
                this.dialogFormVisible = false
                this.$refs['bindForm'].resetFields();
              }
            })
          }
        }
      })
    },
    // 点击取消
    cancel() {
      this.dialogFormVisible = false
      // this.$refs['bindForm'].resetFields();
      this.form = {
        attributeName: '',
        attributeCode: '',
        fieldType: '',
        dictId: '',
        sort: '',
        fieldDesc: ''
      }
    },
    // 搜索框
    querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    filterNode(value, data) {
        if (!value) return true;
        return data.materialType.indexOf(value) !== -1;
    },
    // 获取选中条目
    handleSelectionChange(val) { 
      console.log('选中z', val)
      this.arr = val.map(item => {return item.id})
      console.log('数组id',this.arr)
    },
    // 点击删除按钮
    deleteSpc() {
      if(this.arr.length == 0) {
        this.$message({
          message: '请选择删除数据',
          type: 'warning'
        });
      } else {
        delSpecial(this.arr).then(res => {
          if (res.code === 200) {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.getDetailData(this.treeData.classCode)
          }
        })
      }
    },
    // 点击修改按钮
    edit(e) {
      console.log('修改e',e)
      this.dialogFormVisible = true
      this.titles = '修改'
      // 修改时候弹框数据回显
      this.form = e
    }
  },
}
</script>

<style scoped lang="scss">
.specialAttr {
  height: calc(100vh - 84px);
  padding: 12px;
  box-sizing: border-box;
}
</style>