<!--
 * @Descripttion:
 * @version:
 * @Author: kBank
 * @Date: 2022-11-01 14:08:52
-->
<!--
 * @Descripttion:
 * @version:
 * @Author: kBank
 * @Date: 2022-10-24 15:45:01
-->
<template>
  <div class="page">
    <!-- <topBar v-if="topList.length > 0"
            :topList="topList"
            :moren="moren"></topBar> -->
    <div class="main">
      <div class="maintop">
        <div class="mainbtn">
          <el-button size="small"
                     @click="openDig(1)"
                     v-hasButtons="['GoodsClassifyAdd']"
                     class="addBtn">{{'新增'}}</el-button>
          <el-button size="small"
                     @click="toFixed(selPkId,2)"
                     :disabled="isCopy"
                     v-hasButtons="['GoodsClassifyCopy']"
                     class="copyBtn">{{'复制'}}</el-button>
          <el-button size="small"
                     @click="toTj(0)"
                     :disabled="isCopy"
                     class="tjBtn">{{ '推荐' }}</el-button>
          <el-button size="small"
                     @click="toTj(1)"
                     :disabled="isCopy"
                     class="delBtn"> {{ '取消' }}{{ '推荐' }}</el-button>
        </div>
      </div>
      <div class="maintable">
        <el-table :data="tableData"
        v-loading="loading"
                  style="width: 100%"
                  height="100%"
                  row-key="pkId"
                  lazy
                  ref="table1"
                  :load="load"
                  :header-cell-style="{ background: '#EEEEEE' }"
                  :row-class-name="tableRowClassName"
                  @selection-change="handleSelectionChange"
                  :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column type="selection"
                           width="55"> </el-table-column>
          <el-table-column align="center"
                           prop="classifyImg"
                           :label="'背景图'">
            <template slot-scope="scope">
              <img class="bgImg"
                   :src="scope.row.classifyImg"
                   alt="" />
            </template>
          </el-table-column>
          <el-table-column align="center"
                           prop="classifyName"
                           :label="'名称'">
          </el-table-column>
          <el-table-column align="center"
                           prop="specialAreaName"
                           :label="'所属专区'">
            <template slot-scope="scope">
              <div>
                {{ scope.row.specialAreaName || '--' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           prop="enableState"
                           :label="'显示'">
            <template slot-scope="scope">
              <div :class="scope.row.enableState ? 'isRed' : 'isGreen'">
                {{ scope.row.enableState | isAgree(that) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           prop="sort"
                           sortable
                           :label="'排序'">
          </el-table-column>
          <el-table-column align="center"
                           prop="isRecommend"
                           label="是否推荐">
                           <template slot-scope="scope">
              <div>
                {{ scope.row.isRecommend?'否':'是'}}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           prop="creationTime"
                           :label="'创建日期'">
          </el-table-column>
          <el-table-column align="center"
                           prop="time"
                           :label="'操作'"
                           fixed="right">
            <template slot-scope="scope">
              <div @click="openDig(0,scope.row)"
                   type="text"
                   v-hasButtons="['GoodsClassifyAdd']"
                   style="color:#3181E5;margin-right:10px;cursor: pointer;"
                   size="small">
                {{'新增'}}
              </div>
              <div @click="toFixed(scope.row,1)"
                   type="text"
                   v-hasButtons="['GoodsClassifyUpdate']"
                   style="color:#F3A900;margin-right:10px;cursor: pointer"
                   size="small">
                {{ '修改' }}
              </div>
              <!-- <div @click="toFixed(scope.row,2)"
                   type="text"
                   style="color:#6962F6;margin-right:10px"
                   size="small">
                复制
              </div> -->
              <div @click="handleDelete(scope.row)"
                   type="text"
                   v-hasButtons="['GoodsClassifyDelete']"
                   size="small"
                   style="color:  #C8161D;cursor: pointer">
                {{ '删除' }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <pagination v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getDataList" />
    <el-dialog :title="addOrEdit"
               :close-on-click-modal="false"
               :visible.sync="dialogVisible"
               width="40%"
               center
               :before-close="handleClose">
      <el-form ref="form"
               :rules="rules"
               :model="form"
               label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item :label="'名称'"
                          prop="classifyName">
              <el-input clearable
                        v-model="form.classifyName"
                        :placeholder="'请输入'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24"
                  v-if="hasArea == 1">
            <el-form-item :label="'所属专区'"
                          prop="specialAreaList">
              <el-checkbox-group v-model="form.specialAreaList">
                <el-checkbox v-for="item,index in areaList"
                             :key="item.value"
                             :label="item.value">{{item.label}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="'显示'"
                          prop="enableState">
              <el-select clearable
                         v-model="form.enableState">
                <el-option v-for="item in agreeList"
                           :key="item.val"
                           :label="item.text"
                           :value="item.val"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="'排序'"
                          prop="sort">
              <el-input clearable
                        v-model="form.sort"
                        :placeholder="'请输入'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="'上传图片'"
                          prop="classifyImg">
              <!-- <el-input clearable  v-model="form.name"
                        :placeholder="'请输入'"></el-input> -->
              <!-- <UpDataImg :maxLength="1"
                         ref="upImg"
                         @getImg="getImg"
                         @delImg="delImg"></UpDataImg> -->
              <imageUpload v-model="form.classifyImg" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="handleClose">{{'取消'}}</el-button>
        <el-button type="primary"
                   @click="onSubmit('form')">{{'确认'}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import topBar from '@/components/topBar'
// import UpDataImg from '@/components/upDataImg'
import * as api from '@/api/product.js'
import { areaClassifyUpdate, areaClassifySave } from '@/api/product'
import ImageUpload from '@/components/ImageUpload'

import { specialArea } from '@/api/configManage'
export default {
  name: 'Bzpz',
  components: {
    topBar,
    ImageUpload,
  },
  filters: {
    isAgree(val,that) {
      if (!val) {
        return that.$t('ENU_POPUP_TYPE_1');
      } else {
        return that.$t('ENU_POPUP_TYPE_2');
      }
    },
  },
  data() {
    return {
      that: this,
      isCopy: true,
      creationTime: [],
      select: {
        hierarchy: 0,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
      },
      agreeList: [
        {
          text: '允许',
          val: 0,
        },
        {
          text: '禁止',
          val: 1,
        },
      ],
      addOrEdit: '新增',
      total: 0,
      dialogVisible: false,
      loading:false,
      tableData: [],
      form: {
        classifyImg: '',
        name: '',
        specialAreaList: [],
        coverList: [],
      },
      rules: {
        classifyName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
        ],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        classifyImg: [
          { required: true, message: '请上传图片', trigger: 'change' },
        ],
        enableState: [
          { required: true, message: '请选择显示', trigger: 'change' },
        ],
        specialAreaList: [
          { required: true, message: '请选择所属专区', trigger: 'change' },
        ],
      },
      maps: new Map(),
      areaList: [],
      hasIndex: 0,
      hasArea: 0,
      nowRow: {},
    }
  },
  mounted() {
    // 获取列表
    this.getDataList()
    // 获取专区
    this.getArea()
  },
  methods: {
    toTj(index) {
      let str
      if (index == 1) {
        str = '取消成功'
      } else {
        str = '推荐成功'
      }
      api
        .classifyRecommend({
          isRecommend: index,
          pkId: this.selPkId.pkId,
        })
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: str,
              type: 'success',
            })
          }
        })
    },
    getImg(data) {
      this.form.classifyImg = data
    },
    delImg(data) {
      // console.log('%c [ data ]-261', 'font-size:13px; background:#988b68; color:#dccfac;', data)
      this.form.classifyImg = data
    },
    // 获取专区
    getArea() {
      specialArea().then((res) => {
        this.areaList = res.data
      })
    },
    // 点击修改
    toFixed(row, index) {
      this.nowRow = row
      console.log(
        '%c [ this.nowRow ]-303',
        'font-size:13px; background:#5a7240; color:#9eb684;',
        this.nowRow
      )
      if (row.hierarchy == 0) {
        this.hasArea = 1
      } else {
        this.hasArea = 0
      }
      this.hasIndex = index
      if (this.hasIndex == 1) {
        this.addOrEdit = '修改'
      } else if (this.hasIndex == 2) {
        this.addOrEdit = '复制'
      }
      this.dialogVisible = true
      api.areaClassifyDetail({ pkId: row.pkId }).then((res) => {
        this.form = res.data
        if (res.data.classifyImg) {
          // this.$refs.upImg.noneUploadImg = true
          // this.$refs.upImg.coverList = [{ url: res.data.classifyImg }]
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.nowRow = row

      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        api.areaClassifyDel(row.pkId).then((res) => {
          // this.getDataList()
          console.log(
            '%c [  this.nowRow ]-355',
            'font-size:13px; background:#a953b2; color:#ed97f6;',
            this.nowRow
          )
          if (this.nowRow.pkParent != 0) {
            //区分子父节点 父节点1 子节点空
            const { tree, treeNode, resolve } = this.maps.get(
              this.nowRow.pkParent
            ) //根据父级id取出对应的节点数据
            //将对应父节点下的数据清空，需要在el-table中增加参数 `ref="tableref"`
            this.$set(
              this.$refs.table1.store.states.lazyTreeNodeMap,
              tree.pkId,
              []
            )
            //实现数据的重新加载
            this.load(tree, treeNode, resolve)
          } else {
            this.getDataList()
          }
        })
      })
    },
    onSubmit(formName) {
      console.log(
        '%c [ 22 ]-360',
        'font-size:13px; background:#edff96; color:#ffffda;',
        22
      )
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = ''
          if (this.addOrEdit == '新增' || this.addOrEdit == '复制') {
            url = areaClassifySave
          } else if (this.addOrEdit == '修改') {
            url = areaClassifyUpdate
          }
          url(this.form).then((res) => {
            console.log(
              '%c [ this.nowRow.pkParent ]-381',
              'font-size:13px; background:#2ae4e6; color:#6effff;',
              this.nowRow.pkParent
            )
            if (res.code == 200) {
              this.$message({
                message: res.msg,
                type: 'success',
              })
              // this.dialogVisible = false
              this.handleClose()
              // 充值数据
              this.$refs[formName].resetFields()

              // // 获取列表
              // this.getDataList()

              if (
                this.nowRow.pkParent != 0 &&
                this.nowRow.pkParent != undefined
              ) {
                //区分子父节点 父节点1 子节点空
                const { tree, treeNode, resolve } = this.maps.get(
                  this.nowRow.pkParent
                ) //根据父级id取出对应的节点数据
                //将对应父节点下的数据清空，需要在el-table中增加参数 `ref="tableref"`
                this.$set(
                  this.$refs.table1.store.states.lazyTreeNodeMap,
                  tree.pkId,
                  []
                )
                //实现数据的重新加载
                this.load(tree, treeNode, resolve)
              } else {
                this.tableData = []
                this.getDataList()
              }
            }
          })
        } else {
          return false
        }
      })
    },
    handleClose() {
      this.form = {}
      this.$set(this.form, 'specialAreaList', [])
      this.dialogVisible = false
      this.$refs['form'].clearValidate()
      this.$refs['form'].resetFields()
      // 上传初始化
      // this.$refs.upImg.coverList = []
      // this.$refs.upImg.noneUploadImg = false
    },
    openDig(index, row) {
      this.hasArea = index
      if (index == 0) {
        this.form.pkParent = row.pkId
        this.nowRow = row
      } else {
        this.form.pkParent = 0
      }
      this.dialogVisible = true
      this.addOrEdit = '新增'
    },
    getDataList() {
      this.loading = true
      api
        .areaClassIfyList(Object.assign({}, this.queryParams, this.select))
        .then((res) => {
          res.rows.forEach((item) => {
            item.specialAreaName = []
            item.specialArea.forEach((pat) => {
              this.areaList.forEach((child) => {
                if (pat == child.value) {
                  item.specialAreaName.push(child.label)
                }
              })
            })
            item.specialAreaName = item.specialAreaName.join('/')
          })

          res.rows.forEach((item) => {
            if (item.levelCount > 0) {
              item.hasChildren = true
            } else {
              item.hasChildren = false
            }
          })
          this.tableData = res.rows
          this.total = res.total
          this.loading = false
        })
    },
    //懒加载
    load(tree, treeNode, resolve) {
      this.maps.set(tree.pkId, { tree, treeNode, resolve })
      api.areaClassIfyList({ pkParent: tree.pkId }).then((res) => {
        res.rows.forEach((item) => {
          if (item.levelCount > 0) {
            item.hasChildren = true
          } else {
            item.hasChildren = false
          }
        })
        resolve(res.rows)
      })
    },
    handleSelectionChange(val) {
      console.log(
        '%c [ val ]-458',
        'font-size:13px; background:#8364fe; color:#c7a8ff;',
        val
      )
      this.selPkId = val[0]
      if (val.length > 1) {
        this.isCopy = true
      } else {
        this.isCopy = false
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm( '是否确认导出所有数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return api.exportClassIfy(queryParams)
        })
        .then((response) => {
          this.download(response)
        })
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return 'warning-row'
      } else if (rowIndex % 2 == 0) {
        return 'success-row'
      }
      return ''
    },
  },
}
</script>
<style scoped lang="scss">
::v-deep .el-table .warning-row {
  background: #f9f9f9;
}

::v-deep .el-table .success-row {
  background: #ffffff;
}
::v-deep .el-table thead {
  color: #000000;
}
::v-deep .el-select {
  width: 100%;
}
.uploadIcon ::v-deep .el-upload--picture-card {
  display: none !important; /* 上传按钮隐藏 */
}
.page {
  padding: 20px;
  background: #f9f9f9;
  font-size: 14px;
  .main {
    display: flex;
    flex-direction: column;
    background: #ffffff;
    border-radius: 8px;
    box-shadow: 0px 2px 20px 0px rgba(238, 238, 238, 0.5);
    .maintop {
      display: flex;
      padding: 0px 0 3px 0;
      justify-content: space-between;
      align-items: center;
      .mainbtn {
        .thebtn1 {
          background: #3181e5;
          color: #ffffff;
        }
        .thebtn2 {
          background: #ffad41;
          color: #ffffff;
        }
        .thebtn3 {
          background: #6962f6;
          color: #ffffff;
        }
      }
      .maintitle {
        font-size: 10px;
        font-family: MicrosoftYaHei;
        color: #999999;
      }
    }
  }
  .tem {
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      width: 28px;
      height: 20px;
      margin-right: 3px;
    }
  }
  .isRed {
    color: #ed1d25;
  }
  .isGreen {
    color: #1ab62b;
  }
  .bgImg {
    width: 48px;
    height: 48px;
  }
}
.maintable {
  flex: 1;
  overflow-y: auto;
}
.openClose {
  text-align: right;
  margin-right: 10px;
  color: #3181e5;
}

::v-deep .cell {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
