<template>
  <div class="SippliersClassify">
    <Toptitle title="供应商分类">
      <slot name="titleButton">
        <Button @click="handleCodeRule"
                type="primary"
                ghost
                style="margin-right:10px;">编码规则</Button>
        <Button @click="handleSet()"
                type="primary"
                style="margin-right:10px;">新增分类</Button>
      </slot>
    </Toptitle>
    <div class="content">
      <div class="content_left">
        <Tree :data="treeData"
              children-key='sub'
              :render="renderContent"
              style="width:100%;"
              class="demo-tree-render"></Tree>
      </div>
      <div class="content_right"></div>
    </div>
    <Modal v-model="showModal"
           :title="type==1?'新增分类':'编辑分类'"
           @on-ok="handleModalOk"
           @on-cancel="showModal = false">
      <div class="modal_content">
        <div>
          <span>分类编码: </span>
          <Input type="text"
                 size="small"
                 placeholder="请输入"
                 :disabled="type==2"
                 v-model="form.code"
                 style="width: 220px" />
        </div>
        <div>
          <span>分类名称: </span>
          <Input type="text"
                 size="small"
                 placeholder="请输入"
                 v-model="form.title"
                 style="width: 220px" />
        </div>
      </div>
    </Modal>
    <Modal v-model="showCodeRuleModal"
           title='编码规则'>
      <div class="modal_content">
        <div v-for="item in codeRuleList"
             :key="item.level">
          <span>{{item.level}}级(编码长度): </span>
          <Input type="number"
                 size="small"
                 placeholder="请输入"
                 :disabled="!isAllowEdit"
                 v-model="item.num"
                 style="width: 220px" />
        </div>
      </div>
      <div slot="footer">
        <Button @click="handleCodeRuleModalCancel"
                type="primary"
                ghost
                style="margin-right:10px;">取消</Button>
        <Button @click="handleCodeRuleModalOk"
                type="primary"
                ghost
                style="margin-right:10px;">{{isAllowEdit == false?'修改':'确认'}}</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  name: 'SippliersClassify',
  components: {

  },
  props: {},
  // import引入的组件需要注入到对象中才能使用
  data () {
    // 这里存放数据
    return {
      showModal: false,
      showCodeRuleModal: false,
      isAllowEdit: false,
      type: '',
      form: {
        parent_id: '',
        id: '',
        code: '',
        title: ''
      },
      codeRuleList: [],
      treeData: [
        {
          title: '供应商分类',
          expand: true,
          sub: [],
          render: (h, { root, node, data }) => {
            return h('span', {
              style: {
                display: 'inline-block',
                width: '100%'
              }
            }, [
              h('span', [
                h('Icon', {
                  props: {
                    type: 'ios-folder-outline'
                  },
                  style: {
                    marginRight: '8px'
                  }
                }),
                h('span', data.title)
              ]),
              h('span', {
                style: {
                  display: 'inline-block',
                  // float: 'right',
                  marginRight: '32px'
                }
              })
            ]);
          },
        }
      ],
      buttonProps: {
        type: 'default',
        size: 'small',
      },
      tempRuleList: [],
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.axios({
      method: 'get',
      url: '/api/basic_code_rule',
      params: {
        uid: 2
      }
    }).then((res) => {
      this.codeRuleList = res.data
    }).catch((err) => { });
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.initData()
  },
  methods: {
    initData () {
      this.axios({
        method: 'get',
        url: '/api/basic_supply_list',
      }).then((res) => {
        this.treeData[0].sub = res.data
        // this.openChildrenNode(this.treeData)
      // this.ergodic(this.treeData)
      this.treeData.forEach(item=>{
        item.expand=true;
        if(item.sub.length!=0)
        item.sub.forEach(_item=>{
          _item.expand=true;
          if(_item.sub.length!=0){
            _item.sub.forEach(__item=>{
              __item.expand=true
            })
          }
        })
      })
      }).catch((err) => { });
    },
  ergodic(row){
     row.forEach(item=>{
       if(item.sub.length==0){
         item.expand = true
      
       }else{
         item.expand = true
         this.ergodic(item)
       }
     })
  },
    handleSet () {
      this.type = 1
      this.showModal = true
      this.form.code = ''
      this.form.title = ''
    },
    renderContent (h, { root, node, data }) {
      return h('span', {
        style: {
          display: 'inline-block',
          width: '100%'
        }
      }, [
        h('span', [
          h('Icon', {
            props: {
              type: 'ios-paper-outline'
            },
            style: {
              marginRight: '8px'
            }
          }),
          h('span', `${data.title}(${data.code})`)
        ]),
        h('span', {
          style: {
            display: 'inline-block',
            float: 'right',
            marginRight: '32px'
          }
        }, [
          h('Button', {
            props: { type: 'primary', size: 'small' },
            style: {
              marginRight: '8px'
            },
            on: {
              click: () => {
                this.type = 2
                this.form.parent_id = data.parent_id
                this.form.code = data.code
                this.form.title = data.title
                this.form.id = data.id
                this.showModal = true
              }
            }
          }, '编辑'),
          h('Button', {
            props: { type: 'error', size: 'small' },
            on: {
              click: () => {
                this.handleNodeDele(root, node, data)
              }
            },
          }, '删除')
        ])
      ]);
    },
    append (data) {
      const children = data.children || [];
      children.push({
        code: this.form.code,
        title: this.form.title,
        expand: true
      });
      this.$set(data, 'children', children);
    },
    remove (root, node, data) {
      if (node.children && node.children.length > 0) {
        this.$Message.error('有子集时不可删除')
      } else {
        const parentKey = root.find(el => el === node).parent;
        const parent = root.find(el => el.nodeKey === parentKey).node;
        const index = parent.children.indexOf(data);
        parent.children.splice(index, 1);
      }
    },
    handleCodeRuleModalCancel () {
      this.showCodeRuleModal = false
      this.isAllowEdit = false
      this.codeRuleList = this.tempRuleList
    },
    handleCodeRuleModalOk () {
      this.isAllowEdit = !this.isAllowEdit
      if (!this.isAllowEdit) {
        this.axios({
          method: 'post',
          url: '/api/basic_code_rule_edit',
          data: {
            uid: this.codeRuleList[0].uid,
            rule: this.codeRuleList
          }
        }).then((res) => {
          this.$Message.success(res.msg)
        }).catch((err) => { });
      }
    },
    handleNodeDele (root, node, data) {
      if (data.sub && data.sub.length > 0) {
        this.$Message.error('有子集时不可删除')
      } else {
        this.$Modal.confirm({
          title: '确认删除？',
          content: '此操作无法恢复，请确认！',
          onOk: () => {
            this.axios({
              method: 'get',
              url: '/api/basic_supply_del',
              params: {
                id: data.id
              }
            }).then((res) => {
              if (res.code == 200) {
                this.$Message.success(res.msg)
                this.initData()
              }
            }).catch((err) => { });
          },
          onCancel: () => { }
        })
      }
    },
    handleModalOk () {
      if (this.type == 1) {
        this.axios({
          method: 'post',
          url: '/api/basic_supply_add',
          data: {
            code: this.form.code,
            title: this.form.title
          }
        }).then((res) => {
          // this.$Message.success(res.msg)
          this.initData()
        }).catch((err) => { });
      } else {
        this.axios({
          method: 'post',
          url: '/api/basic_supply_edit',
          data: {
            id: this.form.id,
            code: this.form.code,
            title: this.form.title
          }
        }).then((res) => {
          // this.$Message.success(res.msg)
          this.initData()
        }).catch((err) => { });
      }
    },
    openChildrenNode (arr) {
      arr.forEach(element => {
        element.expand = true
        if (element.sub && element.sub.length > 0) {
          return this.openChildrenNode(element.sub)
        }
      });
    },
    handleCodeRule () {
      this.tempRuleList = JSON.parse(JSON.stringify(this.codeRuleList))
      this.showCodeRuleModal = true
    },
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  beforeCreate () { }, // 生命周期 - 创建之前
  beforeMount () { }, // 生命周期 - 挂载之前
  beforeUpdate () { }, // 生命周期 - 更新之前
  updated () { }, // 生命周期 - 更新之后
  beforeDestroy () { }, // 生命周期 - 销毁之前
  destroyed () { }, // 生命周期 - 销毁完成
  activated () { }, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>
.content {
  width: 100%;
  .content_left {
    width: 70%;
  }
}
.demo-tree-render {
  width: 100%;
}
/deep/.ivu-tree-title {
  width: 100%;
}
.modal_content {
  div {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 10px 0;
  }
}
</style>
