<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :type="type"
    :visible.sync="isVisible"
    width="60%"
    top="50px"
    class="group-dialog"
  >
    <div class="add-dialog-component">
      
      <el-form ref="form" :model="form" label-width="120px" v-if="type == 'add'" >
  <el-form-item label="分类类型：">
    <el-select v-model="form.region" placeholder="请选择活动区域" >
      <el-option label="普通餐饮" value="NORMALSTORE"></el-option>
      <el-option label="快消餐饮" value="FASTSTORE"></el-option>
    </el-select>
  </el-form-item>
</el-form>
<el-form ref="form" :model="forms" label-width="120px"  v-else >
  <el-form-item label="分类类型2：">
    <el-select v-model="forms.region" placeholder="请选择活动区域">
      <el-option label="普通餐饮" value="NORMALSTORE"></el-option>
      <el-option label="快消餐饮" value="FASTSTORE"></el-option>
    </el-select>
  </el-form-item>
</el-form>
      <el-tree
        class="tree-box"
        :data="treeData"
        :props="{ children: 'childs' }"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <div
          slot-scope="{ node, data }"
          class="custom-tree-node"
        >
          <div class="content">
            <template v-if="data.depth < 3">
              <el-input
                v-model="data.categoryName"
                class="input"
                :disabled="isCheck"
                size="mini"
                :placeholder="data.depth | placeholderTips"
              />
            </template>
            <template v-else>
              <div class="level-3-wrap">
                <div class="upload-wrap" :class="isCheck?'disabled':''">
                  <el-upload
                    :headers="headers"
                    :data="dataObj"
                    :multiple="false"
                    :show-file-list="false"
                    :file-list="data.categoryImgArray"
                    :on-success="handleImageSuccess"
                    class="upload-uploader"
                    :action="action"
                  >
                    <img
                      v-if="data.categoryImgArray&&data.categoryImgArray[0].url"
                      :src="data.categoryImgArray&&data.categoryImgArray[0].url"
                    />
                    <i
                      v-else
                      class="el-icon-plus"
                    ></i>
                  </el-upload>
                </div>
                <el-input
                  v-model="data.categoryName"
                  class="textarea-input"
                  type="textarea"
                  resize="none"
                  :disabled="isCheck"
                  size="mini"
                  placeholder="输入三级类别名称"
                />
              </div>
            </template>
          </div>
          <div
            v-if="data.depth * 1 < 3 && !isCheck"
            class="setting-box"
          >
            <el-button
              type="text"
              size="mini"
              @click="() => append(data)"
            >
              {{ data.depth | addTips }}
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => remove(node, data)"
            >
              删除
            </el-button>
          </div>
        </div>
      </el-tree>
      <div class="add-btn-wrap">
        <template v-if="isCheck">
          <el-button
            class="add"
            type="primary"
            size="small"
            @click="close"
          >确定</el-button>
        </template>
        <template v-else>
          <el-button
            v-if="type==='add'"
            class="add"
            type="primary"
            size="small"
            @click="addClassification"
          >添加一级类别名称</el-button>
          <el-button
            type="primary"
            size="small"
            @click="onSubmit"
          >保存</el-button>
        </template>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import Classification from '@/api/Classification.js'
import db from '@/utils/localstorage'
let idx = 1000
let imgId = 1
export default {
  inject:["reload"],
  filters: {
    addTips (depth) {
      depth = depth + ''
      const tipsMp = {
        '1': '添加二级类别名称',
        '2': '添加三级类别名称'
      }
      return tipsMp[depth]
    },
    placeholderTips (depth) {
      depth = depth + ''
      const tipsMp = {
        '1': '输入一级类别名称',
        '2': '输入二级类别名称'
      }
      return tipsMp[depth]
    }
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add'
    }
  },
  data () {
    return {
     forms:{
       region:''
     },
      form: {
          region: 'NORMALSTORE'
        },
      params: {
        categoryName: ''
      },
      customParams: {
        current: 1,
        map: {},
        model: {
          config: '',
          isCustom: true,
          isDelete: 0,
          name: ''
        },
        order: 'descending',
        size: 100,
        sort: 'id'
      },
      treeData: [],
     
      headers: {
        Authorization: ''
      },
      action: `${process.env.VUE_APP_DEV_REQUEST_DOMAIN_PREFIX}/file/upload`,
      dataObj: {
        folderId: 1
      }
    }
  },
  computed: {
    isVisible: {
      get () {
        return this.dialogVisible
      },
      set () {
        this.close()
        this.reset()
      }
    },
    title () {
      const stateMap = {
        'add': '新建类别',
        'edit': '修改类别',
        'check': '查看类别'
      }
      return stateMap[this.type]
    },
    isCheck () {
      return this.type === 'check'
    }
  },
  created () {
    this.headers.token = 'Bearer ' + db.get('TOKEN', '')
    this.headers.tenant = 'MDAwMA=='
    // console.log(this.headers)
  },
  methods: {
    async queryOneCategory (id) {
      console.log(id)
      const res = await Classification.queryOneCategory({
        id
      })
      const resData = res.data.data
      const treeFilter = item => {
        const { categoryName, categoryImg, categoryPath, parentName, depth,posType } = item
        const newMap = {
          depth: depth,
          categoryName,
          categoryPath: categoryPath || '',
          parentName,
          posType,
        }
        if (depth === 3) {
          newMap.categoryImgArray = [
            {
              url: categoryImg
            }
          ]
        }
        if (item.childs && item.childs.length) {
          newMap.childs = item.childs.map(treeFilter)
        }
        return newMap
      }
      if (resData) {
        console.log(resData)
        this.forms.region = resData.posType
        console.log(this.forms.region)
        resData.childs = resData && resData.childs && resData.childs.map(treeFilter)
        this.treeData = [resData]

      } else {
        this.treeData = []
      }
    },
    handleImageSuccess (response, file, fileList) {
      const { url } = response.data
      fileList[0].url = url
    },
    close () {
      this.$emit('close')
    },
    reset () {
      this.treeData = []
    },
    addClassification () {
      this.treeData.push({
        placeholder: '输入一级类别名称',
        addTips: '添加二级类别名称',
        categoryName: '',
        categoryPath: '',
        depth: 1,
        idx: idx++
      })
    },
    append (data) {
      console.log(data)
      const { categoryName } = data
      const depth = data.depth + 1
      let newChild
      if (!data.childs) {
        this.$set(data, 'childs', [])
      }
      if (depth < 3) {
        newChild = {
          placeholder: '输入二级类别名称',
          addTips: '添加三级类别名称',
          depth,
          parentName: categoryName,
          categoryName: '',
          categoryPath: '',
          childs: [],
          idx: idx++
        }
      } else {
        newChild = {
          parentName: categoryName,
          categoryImgArray: [{
            id: imgId++,
            url: ''
          }],
          depth: 3,
          categoryName: '',
          idx: idx++
        }
      }
      data.childs.push(newChild)
    },
    remove (node, data) {
      const parent = node.parent
      const children = parent.data.childs || parent.data
      const index = children.findIndex(d => d.idx === data.idx)
      children.splice(index, 1)
    },
    onSubmit () {
      // console.log(this.form.region)
     
      if (this.type === 'add') {
        this.addGroup()
      } else {
        this.updateGroup()
      }
       this.reload()
      // this.form.region = 'NORMALSTORE'
    },
    async addGroup () {
      const treeFilter = item => {
        const { categoryName, categoryImgArray, categoryPath, parentName, depth } = item
        const newMap = {
          depth: depth,
          categoryName,
          categoryPath: categoryPath || '',
          parentName,
          posType:this.form.region
        }
        if (categoryImgArray) {
          newMap.categoryImg = categoryImgArray[0].url
        }
        if (item.childs && item.childs.length) {
          newMap.childs = item.childs.map(treeFilter)
        }
        return newMap
      }
      const params = this.treeData.map(treeFilter)
      const res = await Classification.addCategory(params)
      const resData = res.data
      const { code } = resData
      if (code === 0) {
        this.isVisible = false
        this.$message({
          message: this.$t('tips.createSuccess'),
          type: 'success'
        })
        this.$emit('success')
      }
      // this.form.region = ''
    },
    async updateGroup () {
      console.log(this.forms.region)
      const treeFilter = item => {
        const { categoryName, categoryImgArray, categoryPath, parentName, depth, id  } = item
        // console.log(posType)
        const newMap = {
          depth: depth,
          categoryName,
          categoryPath: categoryPath || '',
          parentName,
          id,
          posType:this.forms.region
        }
        if (categoryImgArray) {
          newMap.categoryImg = categoryImgArray[0].url
        }
        if (item.childs && item.childs.length) {
          newMap.childs = item.childs.map(treeFilter)
        }
        return newMap
      }
      const params = this.treeData.map(treeFilter)
      
      const res = await Classification.uploadCategory(params)
      const resData = res.data
      const { code } = resData
      if (code === 0) {
        this.isVisible = false
        this.$message({
          message: this.$t('tips.updateSuccess'),
          type: 'success'
        })
        this.$emit('success')
      }
    },
    setParams ({ id }) {
      this.queryOneCategory(id)
    }
  }
}
</script>
<style lang="less">
.add-dialog-component {
  .tree-box {
    .el-tree-node__content {
      margin-bottom: 15px;
      height: auto;
    }
  }
}
</style>
<style lang="less" scoped>
.group-dialog {
  /deep/ .el-dialog {
    min-width: 500px;
    max-width: 600px;
  }
}
.add-dialog-component {
  padding: 15px 20px;
  max-height: 60vh;
  overflow: auto;
  /deep/ .el-tree-node__content{
    &:hover{
      background-color: #fff;
    }
  }
  .tree-box {
    margin: 15px 0;
    .custom-tree-node {
      display: flex;
      width: 100%;
      text-align: left;
      .content {
        flex: 1;
        .input {
          width: 80%;
        }
        .textarea-input {
          width: 100%;
          margin-left: 15px;
          /deep/ textarea {
            height: 80px;
          }
        }
      }
      .level-3-wrap {
        display: flex;
        .upload-wrap {
          position: relative;
          &.disabled::after{
            content: "";
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            z-index: 999;
            background-color: #F5F7FA;
            opacity: .5;
          }
          /deep/ .el-upload {
            border: 1px dashed #d9d9d9;
          }
          i {
            width: 80px;
            height: 80px;
            line-height: 80px;
          }
          img {
            width: 80px;
            height: 80px;
          }
        }
      }
    }
  }
  .add-btn-wrap {
    text-align: center;
  }
}
</style>
