<template>
  <div class="page">
    <topBar
      v-if="topList.length > 0"
      :top-list="topList"
      :moren="moren"
    />
    <div class="thetopbox">
      <el-form label-width="100px">
        <el-row>
          <el-col :span="4">
            <el-form-item :label="'名称'">
              <el-input v-model="queryParams.name" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="4">
            <el-form-item :label="'平台'">
              <el-select
                v-model="queryParams.source"
                clearable
                :placeholder="'请选择'"
              >
                <el-option
                  v-for="item in sourceList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col> -->

          <el-col :span="8">
            <el-form-item :label="'创建日期'" prop="teamCode">
              <el-date-picker
                v-model="queryParams.creationTime"
                type="datetimerange"
                range-separator="——"
                :start-placeholder="'开始日期'"
                :end-placeholder="'结束日期'"
                value-format="yyyy-MM-dd HH:mm:ss"
                :unlink-panels="true"
              />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <div class="searchbox">
              <el-button
                class="my_search"
                @click="
                  () => {
                    getSearch();
                    getCzNum();
                  }
                "
              > {{ '搜索' }}</el-button>
              <el-button class="my_reset" @click="reChongzhi"> {{ '重置' }}</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="main">
      <div class="maintop">
        <div class="mainbtn">
          <el-button
            size="small"
            class="thebtn1"
            @click="addClassify()"
          >{{ '添加' }}</el-button>
        </div>
      </div>
      <div class="maintable">
        <el-table
          ref="table1"
          v-loading="loading"
          :data="tableData"
          height="710px"
          style="width: 100%"
          :header-cell-style="{ background: '#EEEEEE' }"
          row-key="pkId"
          lazy
          :load="load"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
        >
          <!-- <el-table-column prop="colsele" type="selection" width="55">
          </el-table-column> -->
          <!-- type="" -->
          <el-table-column min-width="50px" align="center" prop="sort" :label="'排序'" />
          <el-table-column align="left" prop="title" :label="'名称'">
            <!-- <template slot-scope="scope">
              {{ scope.row.sort }}{{ scope.row.title }}
            </template> -->
          </el-table-column>

          <!-- <el-table-column align="center" prop="sourceVal" :label="'平台'">
          </el-table-column> -->
          <el-table-column align="center" prop="enableStateVal" :label="'显示'">
            <template slot-scope="scope">
              <span v-if="scope.row.enableState == 0" style="color: #009b58">{{
                scope.row.enableStateVal
              }}</span>
              <span v-if="scope.row.enableState == 1" style="color: #c8161d">{{
                scope.row.enableStateVal
              }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="creationTime" :label="'创建日期'" />
          <el-table-column align="center" prop="time" :label="'操作'">
            <template slot-scope="scope">
              <el-button
                style="color: #c8161d"
                type="text"
                size="small"
                class="button-s"
                @click="deleteRow(scope.row)"
              >
                {{'删除'}}
              </el-button>
              <el-button
                type="text"
                size="small"
                class="button-s"
                style="color: #ffad41"
                @click.native.prevent="update(scope.row)"
              >
                {{'修改'}}
              </el-button>
              <el-button
                v-if="scope.row.rank < 3"
                type="text"
                size="small"
                class="button-s"
                style="color: #4391fd"
                @click.native.prevent="addClassify(scope.row)"
              >
                {{'添加'}}
              </el-button>
              <el-button
                v-if="scope.row.enableState == 1"
                style="color: #009b58"
                type="text"
                size="small"
                class="button-s"
                @click="updateStatus(scope.row, 0)"
              >
                {{ '允许' }}
              </el-button>
              <el-button
                v-if="scope.row.enableState == 0"
                style="color: #c8161d"
                type="text"
                size="small"
                class="button-s"
                @click="updateStatus(scope.row, 1)"
              >
                {{'禁止'}}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getSearch"
    />
    <el-dialog
      :title="dialogTitle"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      width="40%"
      center
      :before-close="handleClose"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="'名称'" prop="title">
              <el-input v-model="form.title" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="'排序'" prop="sort">
              <el-input v-model="form.sort" type="number" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="'启用状态'" prop="enableState">
              <el-select
                v-model="form.enableState"
                clearable
                :placeholder="'请选择'"
              >
                <el-option
                  v-for="item in statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="cancels" @click="handleClose">{{ '取消' }}</el-button>
        <el-button
          class="submit"
          style="margin-left: 40px"
          @click="onSubmit('form')"
        >{{ '确认' }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import topBar from '@/components/topBar'
import * as three from '@/api/threegoods'
export default {
  name: 'ClassificationGoods',
  components: {
    topBar
  },
  data() {
    return {
      moren: 'classificationGoods',
      topList: [
        {
          name: '分类维护',
          path: 'classificationGoods'
        }
      ],
      loading:false,
      tableData: [],
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        creationTime: []
      },
      sourceList: [],
      optionList: [],
      total: 0,
      multipleSelection: [],
      maps: new Map(),
      dialogVisible: false,
      form: {
        title: '',
        sort: '',
        enableState: 0
      },
      rules: {
        title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        enableState: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      statusList: [
        { value: 0, label: '启用' },
        { value: 1, label: '禁用' }
      ],
      dialogTitle: '',
      addEdit: ''
    }
  },
  created() {
    this.getSearch()
    this.getOthers()
  },
  methods: {
    // 删除
    deleteRow(row) {
      this.$confirm('是否删除'+'?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((_) => {
        three.deleteWaresCategory({ pkId: row.pkId }).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            // 新增一步解决子级不更新问题

            if (this.maps.get(row.parentId)) {
              const { tree, treeNode, resolve } = this.maps.get(row.parentId) // 根据父级id取出对应的节点数据
              // 将对应父节点下的数据清空，需要在el-table中增加参数 `ref="tableref"`
              this.$set(
                this.$refs.table1.store.states.lazyTreeNodeMap,
                tree.pkId,
                []
              )
              // 实现数据的重新加载
              this.load(tree, treeNode, resolve)
            } else {
              this.getSearch()
            }
          }
        })
      })
    },
    // 添加||修改提交
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = ''
          if (this.addEdit == 1) {
            // 添加
            url = three.saveWaresCategory
          } else {
            // 修改
            url = three.updateWaresCategory
          }
          console.log('🌈', this.form)
          url(this.form).then((res) => {
            if (res.code == 200) {
              this.updateShow = false
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.addEdit = ''
              this.handleClose()
              // 新增一步解决子级不更新问题
              console.log('🌈', this.maps.get(this.form.parentId))
              if (this.maps.get(this.form.parentId)) {
                const { tree, treeNode, resolve } = this.maps.get(
                  this.form.parentId
                ) // 根据父级id取出对应的节点数据
                // 将对应父节点下的数据清空，需要在el-table中增加参数 `ref="tableref"`
                console.log('🌈tree', tree)
                this.$set(
                  this.$refs.table1.store.states.lazyTreeNodeMap,
                  tree.pkId,
                  []
                )
                // //实现数据的重新加载
                this.load(tree, treeNode, resolve)
              } else {
                this.getSearch()
              }
            }
          })
        } else {
          return false
        }
      })
    },
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].clearValidate()
      this.$refs['form'].resetFields()
    },
    // 修改状态
    updateStatus(row, index) {
      console.log('🌈xxxx', this.maps.get(row.parentId))
      this.$confirm('是否修改状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((_) => {
        three
          .categoryUpdateEnable({ pkId: row.pkId, status: index })
          .then((res) => {
            if (res.code == 200) {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              // 新增一步解决子级不更新问题
              if (row.pId) {
                const { tree, treeNode, resolve } = this.maps.get(row.parentId) // 根据父级id取出对应的节点数据
                // 将对应父节点下的数据清空，需要在el-table中增加参数 `ref="tableref"`
                this.$set(
                  this.$refs.table1.store.states.lazyTreeNodeMap,
                  tree.pkId,
                  []
                )
                // 实现数据的重新加载
                this.load(tree, treeNode, resolve)
              } else {
                this.getSearch()
              }
            }
          })
      })
    },
    // 懒加载
    load(tree, treeNode, resolve) {
      this.maps.set(tree.pkId, { tree, treeNode, resolve })
      three
        .getCategoryList({
          parentId: tree.pkId,
          source: this.queryParams.source
        })
        .then((res) => {
          res.rows.forEach((item) => {
            item.pId = 1
            // item.hasChildren = true
            item.hasChildren = item.rank < 3
            // item.hasChildren = item.levelCount > 0 ? true : false;
          })
          // this.tableData.push(...res.rows); // 使用 spread operator 将新数据添加到数组末尾
          resolve(res.rows)
        })
    },
    update(row) {
      this.dialogTitle = '修改'
      this.addEdit = 2
      this.dialogVisible = true
      three.getCategoryDetailList({ pkId: row.pkId }).then((res) => {
        this.form = res.data
      })
    },
    addClassify(row) {
      this.addEdit = 1
      this.dialogTitle = '添加'
      if (row) {
        // 行内添加
        this.form.parentId = row.pkId
      } else {
        this.form.parentId = 0
      }
      this.dialogVisible = true
    },
    getOthers() {
      three.getJxhhSource().then((res) => {
        this.sourceList = res.data
      })
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    reChongzhi() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 50,
        source: 1,
        creationTime: []
      }
      this.getSearch()
    },
    getSearch() {

 this.loading = true
      three.getCategoryList(this.queryParams).then((res) => {
        this.tableData = res.rows
        this.total = res.total
        this.loading = false
        res.rows.forEach((item) => {
          item.pId = 1
          // item.hasChildren = true
          item.hasChildren = item.rank < 3
          // item.hasChildren = item.levelCount > 0 ? true : false;
          item.children = []
        })
      })
    },
    getCzNum() {
      this.queryParams.pageNum = 1
    }
  }
}
</script>

  <style lang="scss" scoped>
.submit {
  width: 209px;
  height: 48px;
  background: #c8161d;
  border-radius: 5px;
  color: #fff;
  font-size: 18px;
  border-color: #c8161d;
  margin-left: 20px;
}
.cancels {
  width: 209px;
  height: 48px;
  background: #cccccc;
  border-radius: 5px;
  color: #fff;
  font-size: 18px;
  border-color: #ccc;
}
::v-deep .dizhi .el-cascader {
  width: 100%;
}
::v-deep .el-range-editor.el-input__inner {
  width: 100%;
}
::v-deep .el-table thead {
  color: #000000;
}
::v-deep .el-table .warning-row {
  background: #f9f9f9;
}
.page {
  padding: 10px 20px;
  background: #f9f9f9;
  font-size: 14px;
  .thetopbox {
    padding: 15px 20px 15px 0;
    background: #ffffff;
    border-radius: 8px;
    .searchbox {
      display: flex;
      align-items: center;
      margin-left: 40px;
    }
    .searchtitle {
      margin-right: 10px;
    }
    .searchbtn {
      background: #08143f;
      color: #ffffff;
    }
  }
  .main {
    //margin-top: 20px;
    background: #f9f9f9;
    //border-radius: 8px;
    //box-shadow: 0px 2px 20px 0px rgba(238, 238, 238, 0.5);

    .maintop {
      display: flex;
      // padding: 10px 0;
      justify-content: space-between;
      align-items: center;
      .mainbtn {
        .thebtn1 {
          color: #ffffff;
          background: #4391fd;
          width: 68px;
          height: 32px;
        }
        .thebtn2 {
          color: #ffffff;
          background: #009b58;
          width: 68px;
          height: 32px;
        }
        .thebtn3 {
          color: #ffffff;
          background: #c8161d;
          width: 68px;
          height: 32px;
        }
      }
    }
  }
}
</style>
