<template>
  <div class="editCom">
    <template v-for="(detailInfo, index) in detailInfos" :key="index">
      <DetailInfo
        :items="detailInfo"
        :rule-form="detailInfo.ruleForm"
        :form-rules="formRules"
        :ref="'detailInfo' + index"
        :disabled="disabled"
      >
        <template #role_id="item">
          <a-select
            :dropdown-match-select-width="false"
            v-model:value="detailInfo.ruleForm[item.key]"
            :placeholder="'请选择' + item.label"
            :disabled="disabled"
            allow-clear
          >
            <a-select-option
              :value="selectItem.role_id"
              v-for="selectItem in roleIdList"
              :key="selectItem.role_id"
            >
              {{ selectItem.name }}
            </a-select-option>
          </a-select>
        </template>
        <template #treetable="item">
          <TreeTable
            class="treeTable"
            :columns="item.columns"
            :table-data="item.tableData"
            ref="treeTable"
            :transfer-dialog="transferDialog"
            :table-option="{
              checkStrictly: false,
              selectTableData: item.selectTableData,
              scroll: { y: 500 }
            }"
          >
            <template #is_add="{ record, index }">
              <a-checkbox v-model:checked="record.is_add"></a-checkbox>
            </template>

            <template #is_del="{ record, index }">
              <a-checkbox v-model:checked="record.is_del"></a-checkbox>
            </template>
            <template #is_edit="{ record, index }">
              <a-checkbox v-model:checked="record.is_edit"></a-checkbox>
            </template>
            <template #is_view="{ record, index }">
              <a-checkbox v-model:checked="record.is_view"></a-checkbox>
            </template>
          </TreeTable>
        </template>
      </DetailInfo>
    </template>

    <div style="display: flex; justify-content: center; gap: 20px">
      <a-button @click="handleback">取消</a-button>
      <a-button @click="handleConfirm" type="primary" :disabled="disabled">确认</a-button>
    </div>
  </div>
</template>

<script>
import {
  userOptions,
  userFormRules,
  roleOptions,
  roleFormRules,
  stationOptions,
  stationFormRules,
  deviceOptions,
  deviceFormRules,
  alarmlogOptions,
  serviceApiOptions,
  serviceApiFormRules
} from '../../public/config/columnList'
import DetailInfo from './DetailInfo.vue'
import { postReq, getReq } from '@/request/api'
const dictionary = {
  menu: '菜单',
  file: '文件',
  role: '角色',
  permission: '权限',
  account: '账户',
  log: '日志',
  server: '服务',
  computer: '主机'
}
export default {
  name: '',
  components: { DetailInfo },
  props: {
    action: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: ''
    },
    record: {
      type: Object,
      default: () => {}
    }
  },

  data() {
    return {
      tip: '正在加载...',
      roleIdList: [],
      transferDialog: false,
      detailInfos: [],
      disabled: true,
      formRules: {},
      apiMethods: {
        // menu: 'menuConfirm',
        user: 'userConfirm',
        role: 'roleConfirm',
        device: 'deviceConfirm',
        station: 'stationConfirm',
        serviceApi: 'serviceApiConfirm'
        // permission: 'permissionConfirm',
      },
      form: {},
      ObjInfo: {},
      loading: false
    }
  },
  computed: {},
  watch: {
    action: {
      handler(n) {
        if (n === 'read') {
          this.disabled = true
        } else {
          this.disabled = false
        }
      },
      immediate: true
    },

    type: {
      async handler(n) {
        switch (n) {
        case 'user':
          this.detailInfos = userOptions
          this.formRules = userFormRules
          break
        case 'menu':
          //   this.detailInfos = menuOptions
          //   this.formRules = menuFormRules
          break
        case 'permission':
       
          break

        case 'role':
          this.detailInfos = roleOptions
          this.formRules = roleFormRules
          break

        case 'station':
          this.detailInfos = stationOptions
          this.formRules = stationFormRules

          break
        case 'device':
          this.detailInfos = deviceOptions
          this.formRules = deviceFormRules
          break
        case 'alarmLog':
          this.detailInfos = alarmlogOptions
          this.formRules = {}
          break
        case 'serviceApi':
          this.detailInfos = serviceApiOptions
          this.formRules = serviceApiFormRules

          break

        default:
          break
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.getRoleIdList()
  },
  methods: {
    async getRoleIdList() {
      const params = {
        page_size: 1000,
        page: 1
      }
      try {
        const res = await getReq('/queryRoleList', params)
        if (res.errcode === 0) {
          this.roleIdList = res.data
        } else {
          const err = { tip: res.errmsg }
          throw err
        }
      } catch (error) {
        this.roleIdList = []
        //统一处理报错提示
      }
    },
    handleChange(value) {
      this.ip = ''
      this.selectComputer = value.option
      this.selectComputer.id = value.option.value
      this.ipList = this.getIpOptions(this.selectComputer.id)
    },

    handleDetailPagesizeChange(val) {
      this.detailInfos[val[1]].list[0].detailPaginationOption = {
        ...this.detailInfos[val[1]].list[0].detailPaginationOption,
        ...val[0]
      }

      if (this.detailInfos[val[1]].list[0].key === 'servebiaoge') {
        //  应用信息中消息模板需要通过接口调用数据
        let arr = {
          ids: this.clickId,
          pageIndex: val[0].current,
          pageSize: val[0].pageSize
        }
      }
    },

    handleRemove(file) {
      const index = this.fileList.indexOf(file)

      this.fileList.splice(index, 1)
    },

    beforeUpload(file, fileList) {
      this.fileList = [...this.fileList, file]

      return false
    },

    //  调用子组件的表单的方法
    async handleConfirm() {
      const result = []
      const { length } = this.detailInfos

      for (let index = 0; index < length; index++) {
        //  校验规则
        const res = await this.$refs[`detailInfo${index}`][0].confirm()
        result.push(res)
        if (!res) {
          break
        }
      }
      if (result.every((item) => item == true)) {
        this.handleSubmit()
      }
    },
    handleSubmit() {
      const { length } = this.detailInfos
      let form = {}
      for (let index = 0; index < length; index++) {
        if (this.$refs[`detailInfo${index}`][0].ruleForm) {
          form = Object.assign(this.$refs[`detailInfo${index}`][0].ruleForm, form)
        } else {
          console.log('对象为空')
        }
      }
      this.form = form
      eval('this.' + this.apiMethods[this.type] + '()')
    },

    async userConfirm() {
      try {
        const menuApi = {
          add: '/insertUser',
          edit: '/updateUser'
        }
        const paramsDate = {
          ...this.form
        }
        if (this.action == 'edit') {
          paramsDate.user_id = this.record.user_id
        }

        const res = await postReq(menuApi[this.action], paramsDate)
        if (res.errcode === 0) {
          setTimeout(() => {
            this.handleback()
          }, 1000)
        } else {
          throw res
        }
      } catch (error) {
        console.log(error, 'userConfirm')
      }
    },
    async roleConfirm() {
      try {
        const menuApi = {
          add: '/insertRole',
          edit: '/updateRole'
        }
        const { selectedRowKeys ,selectedArr} = this.$refs.treeTable[0]
        console.log(selectedRowKeys,selectedArr, 'selectedRowKeys')
        // const  arr = selectedArr.map((item) => ({
        //   ...item,

        //   // 转换操作权限为布尔值
        //   ...this.getPerOperBoolean(item),
        //   // 递归处理children
        //   children: item.children
        //     ? item.children.map((child) => ({
        //       ...child,
        //       ...this.getPerOperBoolean(child),

        //     }))
        //     : []
        // }))
        // console.log(arr,"arr")

        const data=this.filterTreeData(selectedRowKeys,this.$refs.treeTable[0].tableData)
        const  arr = data.map((item) => ({
          ...item,

          // 转换操作权限为布尔值
          ...this.getPerOperBoolean(item),
          // 递归处理children
          children: item.children
            ? item.children.map((child) => ({
              ...child,
              ...this.getPerOperBoolean(child),

            }))
            : []
        }))
        const paramsDate = {
          ...this.form,
          permission:arr
        }

        if (this.action == 'edit') {
          paramsDate.role_id = this.record.role_id
        }

        const res = await postReq(menuApi[this.action], paramsDate)
        if (res.errcode === 0) {
          setTimeout(() => {
            this.handleback()
          }, 1000)
        } else {
          throw res
        }
      } catch (error) {
        console.log(error, 'roleConfirm')
      }
    },
    // 定义筛选树形数据的函数
    filterTreeData(list1, list2) {
      const keySet = new Set(list1);

      // 递归处理节点的函数
      const filterNode = (node) => {
        // 创建新节点对象（浅拷贝）
        const newNode = Object.assign({}, node);

        // 临时删除children属性以便处理
        const { children, ...rest } = newNode;

        // 处理子节点
        let newChildren = [];
        if (children) {
          newChildren = children
            .map((child) => filterNode(child))
            .filter((child) => child !== null);
        }

        // 重建新节点
        const resultNode = Object.assign(rest, {});

        if (newChildren.length > 0) {
          resultNode.children = newChildren;
        }

        // 判断是否保留节点
        if (keySet.has(node.key)) {
          return resultNode;
        }

        // 保留有符合条件子节点的父节点（移除自身key）
        if (newChildren.length > 0) {
          return resultNode;
        }

        return null;
      };

      // 处理根节点
      const result = list2
        .map((node) => filterNode(node))
        .filter((node) => node !== null);

      return result;
    },
    getPerOperBoolean(data) {
      return {
        is_add: Boolean(data.is_add)? '1' : '0',
        is_del: Boolean(data.is_del)? '1' : '0',
        is_edit: Boolean(data.is_edit)?  '1' : '0',
        is_view: Boolean(data.is_view)?  '1' : '0'
      }
    },
    getPermissionData(keys,list){
      const arr=[]
      // list.forEach(item=>{
      //   if(keys.include(item.key)){
      //     arr.push(item)
      //     if()
      //   }

      // })
    },
    async stationConfirm() {
      try {
        const menuApi = {
          add: '/insertStation',
          edit: '/updateStation'
        }
        const paramsDate = {
          ...this.form
        }
        if (this.action == 'edit') {
          paramsDate.station_id = this.record.station_id
        }

        const res = await postReq(menuApi[this.action], paramsDate)
        if (res.errcode === 0) {
          setTimeout(() => {
            this.handleback()
          }, 1000)
        } else {
          throw res
        }
      } catch (error) {
        console.log(error, 'stationConfirm')
      }
    },
    async deviceConfirm() {
      try {
        const menuApi = {
          add: '/insertDevice',
          edit: '/updateDevice'
        }
        const { is_open, rated_capacity, rated_current, rated_voltage, reted_power } = this.form
        const paramsDate = {
          ...this.form,
          is_open: Number(is_open),
          attrs: JSON.stringify({ rated_capacity, rated_current, rated_voltage, reted_power })
        }

        if (this.action == 'edit') {
          paramsDate.device_id = this.record.device_id
        }

        const res = await postReq(menuApi[this.action], paramsDate)
        if (res.errcode === 0) {
          this.$message.success('添加成功')
          setTimeout(() => {
            this.handleback()
          }, 1000)
        } else {
          throw res
        }
      } catch (error) {
        this.$message.error('添加失败')
      }
    },
    async serviceApiConfirm() {
      try {
        const menuApi = {
          add: '/insertServiceApi',
          edit: '/updateServiceApi'
        }
        const paramsDate = {
          ...this.form
        }
        if (this.action == 'edit') {
          paramsDate.api_id = this.record.api_id
        }

        const res = await postReq(menuApi[this.action], paramsDate)
        if (res.errcode === 0) {
          setTimeout(() => {
            this.handleback()
          }, 1000)
        } else {
          throw res
        }
      } catch (error) {
        console.log(error, 'stationConfirm')
      }
    },
    handleback() {
      this.$emit('operateForm', 'back')
    },
    getObjIds(selectKeys) {
      const ids = []
      for (let i = 0; i < selectKeys.length; i++) {
        ids.push({ id: selectKeys[i] })
      }

      return ids
    }
  }
}
</script>
<style lang="scss" scoped>
.editCom {
  // height:400px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.detail-header {
  display: flex;

  span,
  div {
    margin: 10px;
  }
}

:deep(.ant-picker) {
  color: var(--theme-text-default) !important;
}

:deep(.treeTable) {
  width: 750px !important;
}
</style>
