<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 #work_mode="item">
          <a-select
            :dropdown-match-select-width="false"
            v-model:value="workModeIdSelect"
            :placeholder="'请选择' + item.label"
            :disabled="disabled"
            allow-clear
          >
            <a-select-option
              :value="selectItem.value"
              v-for="selectItem in workModeList"
              :key="selectItem.value"
            >
              {{ selectItem.label }}
            </a-select-option>
          </a-select>
        </template>

        <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 },
              select:false
            }"
          >
            <template #is_add="{ record }">
              <a-checkbox v-model:checked="record.is_add"></a-checkbox>
            </template>

            <template #is_del="{ record }">
              <a-checkbox v-model:checked="record.is_del"></a-checkbox>
            </template>
            <template #is_edit="{ record }">
              <a-checkbox v-model:checked="record.is_edit"></a-checkbox>
            </template>
            <template #is_view="{ record }">
              <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,
  syslogOptions
} 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 {
      workModeIdSelect: undefined,

      workModeList: [
        {
          label: '峰谷套利',
          value: '1'
        },
        {
          label: '配网增容',
          value: '2'
        },
        {
          label: '应急供电',
          value: '3'
        },
        {
          label: '并网保电',
          value: '4'
        },
        {
          label: '运营支撑',
          value: '5'
        }
      ],

      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: {
    workModeIdSelect: {
      async handler(n, o) {
        if ( n !== o) {
          this.detailInfos[0].ruleForm.policy_id = ''
        }
        switch (n) {
         
        case '1':
          this.detailInfos[0].list[this.detailInfos[0].list.length - 1].type = 'select'
          this.detailInfos[0].list[this.detailInfos[0].list.length - 1].list =
              await this.getPolicyList(1)

          break
        case '5':
          this.detailInfos[0].list[this.detailInfos[0].list.length - 1].type = 'select'
          this.detailInfos[0].list[this.detailInfos[0].list.length - 1].list =
              await this.getPolicyList(5)

          break
        default:
          this.detailInfos[0].list[this.detailInfos[0].list.length - 1].type = 'unshow'
          break
        }
      }
      // immediate: true
    },

    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
          this.workModeIdSelect = this.detailInfos[0].ruleForm['work_mode']
          console.log(stationOptions)

          break
        case 'device':
          this.detailInfos = deviceOptions
          this.formRules = deviceFormRules
          break
        case 'alarmLog':
          this.detailInfos = alarmlogOptions
          this.formRules = {}
          break
        case 'syslog':
          this.detailInfos = syslogOptions
          this.formRules = {}
          break

        case 'serviceApi':
          this.detailInfos = serviceApiOptions
          this.formRules = serviceApiFormRules

          break

        default:
          break
        }
      },
      immediate: true
    }
  },
  mounted() {
    if(this.type == 'user'||this.type == 'role'){
      this.getRoleIdList()

    }
  },
  unmounted() {
    console.log('modal')
  },
  methods: {
    async getPolicyList(type) {
      let list = []
      try {
        const res = await getReq('/queryPolicyByType', { type })
        if (res.errcode == 0) {
          list = res.data.map((item) => {
            return { label: item.name, value: item.policy_id }
          })
        }
      } catch (error) {
        console.log(error)
      }

      return list
    },
    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) {
          this.$message.success('操作成功')
          setTimeout(() => {
            this.handleback()
          }, 1000)
        } else {
          throw res
        }
        
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    async roleConfirm() {
      try {
        const menuApi = {
          add: '/insertRole',
          edit: '/updateRole'
        }
        const { selectedRowKeys } = this.$refs.treeTable[0]

        const data = this.filterCheckedTree( 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
        }
        console.log(arr,"aaaaaaaaaaa")
        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('操作失败')
      }
    },
    // 定义筛选树形数据的函数
    filterCheckedTree(data) {
      return data
        .filter((item) => item.checked) // 过滤当前层级 checked 为 true 的节点
        .map((item) => {
          // 深拷贝节点（避免修改原数据）
          const newItem = { ...item };
          // 递归处理 children
          if (newItem.children && newItem.children.length > 0) {
            newItem.children = this.filterCheckedTree(newItem.children);
          }
          return newItem;
        });
    },
    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,
          status:Number(this.form.status),
          work_mode:this.workModeIdSelect
        }
        if (this.action == 'edit') {
          paramsDate.station_id = this.record.station_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 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
    },
    //移除校验
    clearValidate() {
      for (let i = 0; i < this.detailInfos.length; i++) {
        // console.log(`detailInfo${i}`);

        this.$refs[`detailInfo${i}`].handleReset()
      }
    }
  }
}
</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>
