<template>
  <div style="width: 100%; height: 100%; box-sizing: border-box; padding: 20px">
    <zj-page-container direction="row">
      <div class="catalogue" style="padding-right: 0px">
        <zj-page-container>
          <div style="padding: 0 10px 10px; display: flex">
            <el-button icon="el-icon-refresh-right" size="small" @click="refreshDepartment"
              style="padding: 9px 10px; margin-right: 6px"></el-button>
            <el-input placeholder="输入关键字进行过滤" size="small" clearable v-model="filterText"> </el-input>
          </div>
          <zj-page-fill>
            <el-tree :data="listTree" :props="defaultProps" default-expand-all highlight-current
              :expand-on-click-node="false" :filter-node-method="filterNode" @node-click="handleNodeClick"
              node-key="categoryId" ref="listTree">
              <div class="custom-tree-node" slot-scope="{ node, data }">
                <span>
                  <i :class="data.children && data.children.length > 0 ? 'el-icon-folder-opened' : 'el-icon-document-remove'
              "></i>
                  <span>{{ node.label }}</span>
                </span>
                <span v-if="data.level == 2 || data.level == 3">
                  <el-button v-if="data.level == 2" type="text" size="mini" @click="addChClass(data)"> 添加 </el-button>
                  <el-button v-if="data.level == 3" type="text" size="mini" @click="editClass(data)"> 编辑 </el-button>
                  <el-popconfirm v-if="data.level == 3" style="margin-left: 10px" title="确定删除吗？"
                    @confirm="handleDelete(data)">
                    <el-button v-if="data.level == 3" slot="reference" size="mini" type="text"> 删除 </el-button>
                  </el-popconfirm>
                </span>
              </div>
            </el-tree>
          </zj-page-fill>
        </zj-page-container>
      </div>
      <zj-page-fill v-loading="!showList">
        <template-page v-if="showList && item && item.typeAttribute" ref="pageRef" :getList="getListRight"
          :exportList="exportList" :columnParsing="columnParsing" :optionsEvensGroup="optionsEvensGroup"
          :tableAttributes="tableAttributes" :tableEvents="tableEvents" :operationColumnWidth="200"
          :operation="operation()" :recordsHook="recordsHook" :replaceOrNotMap="true" :customModuleName="`${$route.meta.title}_${item ? ['规格', '其他'][typeAttribute[item.typeAttribute]] : ''
              }`" :setModuleId="`${$route.meta.moduleId}_${item ? item.typeAttribute : ''}`">
        </template-page>
      </zj-page-fill>
    </zj-page-container>
    <el-dialog :title="formData.categoryId ? '编辑' : '新建'" :modal="true" width="600px" :visible.sync="formDialog"
      :before-close="formCancel" :close-on-click-modal="false">
      <zj-form-container v-if="formDialog" ref="formRef" :form-data="formData" :styleSwitch="false">
        <zj-form-module label-width="120px" :showPackUp="false" :form-data="formData" :form-items="formItems">
        </zj-form-module>
      </zj-form-container>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="formCancel">取 消</el-button>
        <el-button size="mini" @click="formConfirm" type="primary">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import import_mixin from '@/components/template/import_mixin.js'
import TemplatePage from '@/components/template/template-page-1.vue'
import { treeToList } from '@/utils/util'
import {
  tradeList,
  tradeListPage,
  tradePageExport,
  tradeListOtherPage,
  tradePageOtherExport,
  serviceCategoryDetail,
  serviceCategoryItemAdd,
  serviceCategoryItemUpdate,
  serviceCategoryItemDel
} from '@/api/tradeInConfig.js'
import formItems from '../mixins/formItems.js'
export default {
  mixins: [import_mixin, formItems],
  components: {
    TemplatePage
  },
  data() {
    return {
      // 事件组合
      optionsEvensGroup: [],
      // 表格属性
      tableAttributes: {},
      // 表格事件
      tableEvents: {},
      // 重新加载列表
      showList: true,
      //**部门树 */
      filterText: '',
      list: [],
      listTree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      item: null,
      typeAttribute: {
        SPEC: 0,
        OTHER: 1
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.listTree.filter(val)
    },
    item(val) {
      this.showList = false
      if (val) {
        this.$nextTick(() => {
          this.showList = true
        })
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      tradeList().then(res => {
        this.list = treeToList(res.data)
        this.listTree = res.data
        this.listTree.map(item => {
          ; (item.children || []).map(item2 => {
            ; (item2.children || []).map(item3 => {
              if (!this.item) {
                this.item = item3
                serviceCategoryDetail({ categoryId: item3.categoryId }).then(res => {
                  this.item = res.data
                  this.$nextTick(() => {
                    this.$refs.listTree.setCurrentKey(this.item?.categoryId || '')
                  })
                })
              }
            })
          })
        })
      })
    },
    refreshDepartment() {
      this.getList()
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 选择部门
    handleNodeClick(data) {
      if (data.level === 3) {
        serviceCategoryDetail({ categoryId: data.categoryId }).then(res => {
          this.item = res.data
        })
      } else {
        this.$refs.listTree.setCurrentKey(this.item?.categoryId || '')
      }
    },
    exportList(...p) {
      return [tradePageExport, tradePageOtherExport][
        this.typeAttribute[this.item.typeAttribute]
      ](...p)
    },
    // 列表请求函数
    getListRight(p, cb) {
      p.params.push({ param: 'service_category_id', compare: '=', value: this.item.categoryId })
      cb && cb(p)
      return [tradeListPage, tradeListOtherPage][
        this.typeAttribute[this.item.typeAttribute]
      ](p)
    },
    recordsHook(list) {
      return [
        {
          "dictName": "",
          "price": 0,
          "companyName": JSON.parse(localStorage.getItem('greemall_user')).companyName,
          "categoryName": this.item?.name || '',
          "serviceCategoryId": this.item?.categoryId || '',
          "status": 'ON',
          "typeAttribute": this.item?.typeAttribute,
          "remark": "",
          "maxPrice":"",
          "minPrice":"",
          isRowEdit: true
        },
        ...list.map(item => ({ ...item, isRowEdit: false }))
      ]
    },
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      if (item.jname === 'dictName') {
        defaultData.render = (h, { row, index, column }) => {
          if (row.isRowEdit) {
            return (
              <div class="redbordererr">
                <el-input
                  value={row[column.columnAttributes.prop]}
                  onInput={val => {
                    row[column.columnAttributes.prop] = val
                  }}
                  placeholder="请输入内容"
                ></el-input>
              </div>
            )
          } else {
            return <div style="padding:0 6px;">{row[column.columnAttributes.prop]}</div>
          }
        }
      }
      if (item.jname === 'remark') {
        defaultData.render = (h, { row, index, column }) => {
          if (row.isRowEdit) {
            return (
              <div class="redbordererr">
                <el-input
                  value={row[column.columnAttributes.prop]}
                  onInput={val => {
                    row[column.columnAttributes.prop] = val
                  }}
                  placeholder="请输入内容"
                ></el-input>
              </div>
            )
          } else {
            return <div style="padding:0 6px;">{row[column.columnAttributes.prop]}</div>
          }
        }
      }
      if (item.jname === 'status') {
        defaultData.render = (h, { row, index, column }) => {
          if (row.isRowEdit) {
            return (
              <div class="redbordererr">
                <el-select
                  value={row[column.columnAttributes.prop]}
                  onInput={val => {
                    row[column.columnAttributes.prop] = val
                  }}
                  placeholder="请选择"
                >
                  {[
                    { label: '有效', value: 'ON' },
                    { label: '无效', value: 'OFF' }
                  ].map((item, index_) => (
                    <el-option key={index_} label={item.label} value={item.value}></el-option>
                  ))}
                </el-select>
              </div>
            )
          } else {
            return <div style="padding:0 6px;">{row[column.columnAttributes.prop]}</div>
          }
        }
      }
      if (item.jname === 'price') {
        defaultData.render = (h, { row, index, column }) => {
          if (row.isRowEdit) {
            return (
              <div class="redbordererr">
                <el-input
                  value={row[column.columnAttributes.prop]}
                  onInput={val => {
                    row[column.columnAttributes.prop] = val
                  }}
                  placeholder="请输入内容"
                  type="number"
                ></el-input>
              </div>
            )
          } else {
            return (
              <div style="padding:0 6px;">{row[column.columnAttributes.prop]}</div>
            )
          }
        }
      }
      return defaultData
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            {index === 0 || row.isRowEdit ? (
              <zj-button
                useLoading={false}
                parameter={[row]}
                buttonAttributes={{
                  size: 'mini',
                  type: 'primary'
                }}
                buttonEvents={{
                  click: row => {
                    if (this.jiaoyan(row)) {
                      ;[serviceCategoryItemAdd, serviceCategoryItemUpdate]
                      [row.id ? 1 : 0]({
                        ...row,
                        status: row.status == '有效' ? 'ON' : row.status == '无效' ? 'OFF' : row.status
                      })
                        .then(res => {
                          this.$message({
                            type: 'success',
                            message: `保存成功!`
                          })
                          this.$refs.pageRef.refreshList()
                        })
                    }
                  }
                }}
              >
                保存
              </zj-button>
            ) : null}
            {!row.isRowEdit ? (
              <zj-button
                useLoading={false}
                parameter={[row]}
                buttonAttributes={{
                  size: 'mini',
                  type: 'primary'
                }}
                buttonEvents={{
                  click: row => {
                    row.isRowEdit = true
                  }
                }}
              >
                编辑
              </zj-button>
            ) : null}
            {index !== 0 ? (
              <el-popconfirm
                icon="el-icon-info"
                icon-color="red"
                title="这是一段内容确定删除吗？"
                onConfirm={() => {
                  serviceCategoryItemDel({
                    categoryId: row.id
                  }).then(res => {
                    this.$message({
                      type: 'success',
                      message: `删除成功!`
                    })
                    this.$refs.pageRef.refreshList()
                  })
                }}
              >
                <zj-button
                  slot="reference"
                  buttonAttributes={{
                    size: 'mini',
                    type: 'danger'
                  }}
                >
                  删除
                </zj-button>
              </el-popconfirm>
            ) : null}
          </div>
        )
      }
    },
    jiaoyan(row) {
      try {
        ;['dictName', 'price'].map(key => {
          if (row[key] === undefined || row[key] === null || row[key] === '') {
            throw new Error(
              {
                dictName: '字典值',
                price: ["回收价格（元/台）", "增减费用（元/台）"][this.typeAttribute[this.item.typeAttribute]],
              }[key]
            )
          }
        })
        return true
      } catch (err) {
        this.$message({
          type: 'error',
          message: `缺少参数【${err.message}】!`
        })
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.catalogue {
  width: 300px;
  height: 100%;
  box-sizing: border-box;
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
