<template>
  <div class="app-container">
    <div class="container-main" style="justify-content: flex-start;">
      <!--侧边部门数据-->
      <div class="elect-cont-right">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle" class="head-search">
            <!-- 搜索 -->
            <el-input v-model="query.blurry" size="small" clearable placeholder="输入全宗名称搜索" prefix-icon="el-icon-search" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
            <date-range-picker v-model="blurryTime" class="date-item" />
            <el-select v-model="query.status" clearable size="small" placeholder="状态" class="filter-item" style="width: 100px" @change="crud.toQuery">
              <i slot="prefix" class="iconfont icon-zhuangtai" />
              <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
            </el-select>
            <rrOperation />
          </div>
          <crudOperation :permission="permission">
            <template v-slot:middle>
              <el-button slot="reference" size="mini" :loading="crud.delAllLoading" :disabled="crud.selections.length === 0" @click="toDelete(crud.selections)">
                <i class="iconfont icon-shanchu" />
                删除
              </el-button>
            </template>
            <template v-slot:right>
              <el-button :loading="crud.downloadLoading" size="mini" :disabled="crud.selections.length === 0" @click="doExport(crud.selections)">
                <i class="iconfont icon-daochu" />
                导出
              </el-button>
            </template>
          </crudOperation>
        </div>
        <div class="container-right">
          <span class="right-top-line" />
          <span class="left-bottom-line" />
          <!-- 表单渲染 -->
          <el-dialog :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" class="group-form">
            <span class="dialog-right-top" />
            <span class="dialog-left-bottom" />
            <div class="setting-dialog">
              <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="90px">
                <el-row>
                  <el-form-item label="全宗号" prop="fondsNo">
                    <el-input v-model="form.fondsNo" />
                  </el-form-item>
                </el-row>
                <el-form-item label="全宗名称" prop="fondsName" class="form-item-style">
                  <el-input v-model="form.fondsName" />
                </el-form-item>
                <el-form-item label="全宗简称" prop="fondsNameAbbr">
                  <el-input v-model="form.fondsNameAbbr" />
                </el-form-item>
                <el-form-item label="排序" prop="fondsOrders" class="form-item-style">
                  <el-input-number
                    v-model.number="form.fondsOrders"
                    :min="0"
                    :max="999"
                    controls-position="right"
                  />
                </el-form-item>
                <el-form-item label="状态" prop="fondsStatus">
                  <el-radio-group v-model="form.fondsStatus">
                    <el-radio :label="1">启用</el-radio>
                    <el-radio :label="0">停用</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="fondsRemarks">
                  <el-input v-model="form.fondsRemarks" style="width: 586px;" rows="5" type="textarea" />
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="text" @click="crud.cancelCU">取消</el-button>
                <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确定</el-button>
              </div>
            </div>
          </el-dialog>
          <el-table ref="table" v-loading="crud.loading" highlight-current-row style="width: 100%;" :data="crud.data" @selection-change="crud.selectionChangeHandler" @current-change="handleCurrentChange">
            <el-table-column type="selection" align="center" width="55" />
            <el-table-column prop="fondsNo" label="全宗号" />
            <el-table-column prop="fondsName" label="全宗名称" min-width="120" />
            <el-table-column prop="deptsCount" label="部门" />
            <el-table-column prop="fondsOrders" label="排序" />
            <el-table-column label="状态" align="center" prop="fondsStatus" width="60">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.fondsStatus" active-color="#409EFF" inactive-color="#F56C6C" :active-value="1" :inactive-value="0" @change="changeStatus(scope.row, scope.row.fondsStatus)" />
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建日期">
              <template slot-scope="scope">
                <div>{{ scope.row.createTime | parseTime }}</div>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination />
        </div>
      </div>
      <div class="elect-cont-left role-cont-left" style="margin: 0 0 0 20px;">
        <div class="container-left">
          <span class="right-top-line" />
          <span class="left-bottom-line" />
          <div slot="header" class="tree-tab">
            <el-tooltip class="item" effect="dark" content="选择门类关联" placement="top">
              <span class="role-span role-tab-active">门类关联</span>
            </el-tooltip>
            <!-- v-permission="['admin','fonds:edit']" -->
            <el-button
              :disabled="!showButton"
              :loading="categoryLoading"
              size="mini"
              @click="saveCategory"
            >保存</el-button>
          </div>
          <!-- :load="getCategoryDataList" @check="menuChange" default-expand-all :default-checked-keys="categoryIds"-->
          <el-tree
            ref="category"
            lazy
            :data="categoryDatas"
            :load="getCategoryDataList"
            :default-checked-keys="categoryIds"
            check-strictly
            show-checkbox
            node-key="id"
            highlight-current
            :props="defaultProps"
            @check="categoryChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import crudfonds from '@/api/system/fonds'
import { FetchCategoryMenu, FetchCategoryMenuChildren } from '@/api/system/category/category'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker'
import { exportFile } from '@/utils/index'
import qs from 'qs'
import { mapGetters } from 'vuex'

const defaultForm = { id: null, fondsName: null, fondsNameAbbr: null, fondsNo: null, fondsOrders: 999, fondsStatus: null, fondsRemarks: null }
export default {
  name: 'Group',
  components: { pagination, crudOperation, rrOperation, DateRangePicker },
  cruds() {
    return CRUD({ title: '全宗', idField: 'fondsId', url: 'api/fonds/initFondsList', sort: 'update_time,asc', crudMethod: { ...crudfonds }, optShow: {
      add: true,
      edit: true,
      del: false,
      reset: true,
      download: false,
      group: false
    }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'cnName',
        isLeaf: (data, node) => {
          if (data.isType === 2) {
            return true
          }
        }
      },
      currentId: 0, categoryLoading: false, showButton: false,
      categoryDatas: [], categoryIds: [], depts: [], deptDatas: [], // 多选时使用
      categoryAllData: [],
      permission: {
        add: ['admin', 'fonds:add'],
        edit: ['admin', 'fonds:edit'],
        del: ['admin', 'fonds:del']
      },
      rules: {
        fondsNo: [
          { required: true, message: '请输入全宗号', trigger: 'blur' }
        ],
        fondsName: [
          { required: true, message: '请输入全宗名称', trigger: 'blur' }
        ],
        fondsNameAbbr: [
          { required: true, message: '请输入全宗简称', trigger: 'blur' }
        ],
        fondsOrders: [
          { required: true, message: '请输入排序', trigger: 'blur', type: 'number' }
        ],
        fondsStatus: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      enabledTypeOptions: [
        { key: '1', display_name: '启用' },
        { key: '0', display_name: '停用' }
      ],
      blurryTime: null,
      deleteData: [], // 删除选中的data
      chooseNode: null,
      categoryTreeData: []
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  created() {
  },
  mounted() {
    FetchCategoryMenu().then(res => {
      this.categoryDatas = this.filterData(res)
    })
  },
  methods: {
    getCategoryDataList(node, resolve) {
      console.log('node', node)
      console.log('node.childNodes', node.childNodes)
      FetchCategoryMenuChildren(node.data.id ? node.data.id : 0).then(res => {
        if (res.length !== 0 && res[0].isType === 3) {
          return resolve([])
        }
        resolve(res)
      })
    },
    filterData(data) {
      return data.filter(node => {
        this.$set(node, 'isChecked', false)
        if (node.children && node.children.length > 0) {
          node.children = this.filterData(node.children) // 递归处理子节点
        }
        return node.isType !== 3 // 过滤掉isType为3的节点
      })
    },
    // getCategoryDataList(node, resolve) {
    //   resolve(this.categoryTreeData)
    // },
    [CRUD.HOOK.beforeRefresh]() {
      if (this.blurryTime) {
        this.crud.query.startTime = this.blurryTime[0]
        this.crud.query.endTime = this.blurryTime[1]
      }
    },
    [CRUD.HOOK.afterRefresh]() {
      this.$refs.category.setCheckedKeys([])
    },
    // 新增前
    [CRUD.HOOK.beforeToAdd](crud, form) {
    },
    // 编辑前
    [CRUD.HOOK.beforeToEdit](crud, form) {
      form.id = form.fondsId
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
    },
    // 触发单选
    handleCurrentChange(val) {
      if (val) {
        const _this = this
        // 清空菜单的选中

        this.$refs.category.setCheckedKeys([])
        // 保存当前的角色id
        this.currentId = val.fondsId
        console.log('val', val)
        console.log('this.currentId', this.currentId)
        console.log('this.categoryDatas', this.categoryDatas)
        this.categoryIds = []
        // this.categoryDatas.forEach(function(data) {
        //   _this.categoryIds.push(data.id)
        // })
        // console.log(_this.categoryIds)
        crudfonds.FetchFondsDetail({ id: this.currentId }).then((res) => {
          if (res.categorys) {
            res.categorys.forEach(function(data) {
              _this.categoryIds.push(data.id)
            })
            this.$refs.category.setCheckedKeys(_this.categoryIds)
          }
          console.log(_this.categoryIds)
        }).catch(err => {
          console.log(err)
        })
        this.showButton = true
      }
    },
    toDelete(datas) {
      this.deleteData = datas
      this.$confirm('此操作将删除当前所选' + this.crud.title + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        this.crud.delAllLoading = true
        const ids = []
        this.deleteData.forEach(val => {
          ids.push(val.fondsId)
        })
        crudfonds.del(ids).then((res) => {
          console.log('res', res)
          if (res !== 0) {
            this.$message({ message: '删除成功', type: 'success', offset: 8 })
          } else {
            this.$message({ message: '删除失败', type: 'error', offset: 8 })
          }
          this.crud.delAllLoading = false
          this.crud.refresh()
        }).catch(err => {
          this.crud.delAllLoading = false
          console.log(err)
        })
      }).catch(() => {
      })
    },
    changeStatus(data, val) {
      data.id = data.fondsId
      this.$confirm('此操作将禁用 / 启用全宗 “' + data.fondsName + '”' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        crudfonds.FetchUpdateFondsStatus(data).then(res => {
          this.$message({ message: '修改成功', type: 'success', offset: 8 })
        }).catch(() => {
          data.fondsStatus = !data.fondsStatus
        })
      }).catch(() => {
        this.$message({ message: '已取消修改', offset: 8 })
        data.fondsStatus = data.fondsStatus ? 0 : 1
      })
    },
    doExport(data) {
      crud.downloadLoading = true
      this.$confirm('此操作将导出所选数据' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const ids = []
        data.forEach(val => {
          ids.push(val.fondsId)
        })
        const params = {
          'fondsIds': ids
        }
        exportFile(this.baseApi + '/api/fonds/download?' + qs.stringify(params, { indices: false }))
      }).catch(() => {
      })
    },
    findNodeById(id, nodes) {
      for (const node of nodes) {
        if (node.id === id) {
          return node
        } else if (node.children.length > 0) {
          const foundNode = this.findNodeById(id, node.children)
          if (foundNode) {
            return foundNode
          }
        }
      }
      return null
    },
    getAllChildIds(id, nodes) {
      const node = this.findNodeById(id, nodes)
      if (node) {
        let childIds = [node.id]
        for (const child of node.children) {
          childIds = childIds.concat(this.getAllChildIds(child.id, nodes))
        }
        return childIds
      } else {
        return []
      }
    },
    categoryChange(categorys) {
      console.log('categorys.id', categorys.id)
      // console.log(this.categoryDatas)
      // const childrenIds = this.getAllChildIds(categorys.id, this.categoryDatas)
      // console.log('childrenIds', childrenIds)
      // console.log(this.$refs.category.getCheckedKeys())
      // this.categoryIds = this.$refs.category.getCheckedKeys()

      FetchCategoryMenuChildren(categorys.id).then(childIds => {
        const i = this.categoryIds.indexOf(categorys.id)
        if (i !== -1) {
          this.categoryIds.splice(i, 1)
          for (let i = 0; i < childIds.length; i++) {
            const index = this.categoryIds.indexOf(childIds[i].id)
            if (index !== -1) {
              this.categoryIds.splice(index, 1)
            }
          }
        } else {
          this.categoryIds.push(categorys.id)
          for (let i = 0; i < childIds.length; i++) {
            const index = this.categoryIds.indexOf(childIds[i].id)
            if (index === -1) {
              this.categoryIds.push(childIds[i].id)
            }
          }
        }
        this.$refs.category.setCheckedKeys(this.categoryIds)
      })
    },
    // 保存菜单
    saveCategory() {
      this.categoryLoading = true
      const fonds = { id: this.currentId, categorys: [] }
      // 得到已选中的 key 值
      this.categoryIds.forEach(function(id) {
        const categorys = { id: id }
        fonds.categorys.push(categorys)
      })
      console.log(fonds)
      crudfonds.FetchFondsCategory(fonds).then(() => {
        this.$message({ message: '保存成功', type: 'success', offset: 8 })
        this.categoryLoading = false
        this.update()
      }).catch(err => {
        this.categoryLoading = false
        console.log(err.response.data.message)
      })
    },
    // 改变数据
    update() {
      // 无刷新更新 表格数据
      crudfonds.FetchInitFondsList().then(res => {
        console.log(res)
        for (let i = 0; i < this.crud.data.length; i++) {
          if (res.fondsId === this.crud.data[i].fondsId) {
            this.crud.data[i] = res
            break
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.group-form{
  .el-form-item{
    &:nth-child(odd){
      margin-right: 0;
    }
    &.form-item-style{
      margin-right: 40px;
    }
  }
}

.tree-tab span.role-span.role-tab-active{
  border-bottom: none;
}
</style>
