<template>
  <h-table
    stripe
    :data-source="list"
    :columns="columns"
    row-key="key"
    :bordered="false"
    :pagination="false"
    size="small"
  >
    <template #bodyCell="{ record, index, column, text }">
      <template v-if="['allow', 'reject', 'other'].includes(column.dataIndex)">
        <h-radio
          :checked="record.checkStatus === text"
          :value="text"
          :disabled="isStatus === 'view'"
          @change="handleChange(index, text, record.key)"
        />
      </template>
      <template v-else>
        {{ record.value }}
      </template>
    </template>
  </h-table>
</template>
<script lang="ts">
import { reactive, ref, defineComponent, inject, nextTick, toRefs } from 'vue';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { useHttp } from '@crami/http';
import { Radio as HRadio, Table as HTable } from '@crami/ui';
import { cloneDeep } from 'lodash-es';
import { useI18n } from '@crami/locale';
export default defineComponent({
  name: 'PermissionConfig',
  components: {
    HTable,
    HRadio,
  },
  props: {
    permissionData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    eid: {
      type: String,
      default: '',
    },
  },
  setup(props, { emit }) {
    const { t } = useI18n();
    // 表单状态：add|edit|view
    const isStatus = inject('isStatus');
    // 表格配置部分
    const columns = reactive([
      {
        dataIndex: 'value',
        title: t('permission.common.permission'),
        align: 'center',
        minWidth: 80,
        width: -1,
      },
      {
        dataIndex: 'allow',
        title: t('permission.common.allow'),
        align: 'center',
        width: '150px',
      },
      {
        dataIndex: 'reject',
        title: t('permission.common.reject'),
        align: 'center',
        width: '150px',
      },
      {
        dataIndex: 'other',
        title: t('permission.common.nothing'),
        align: 'center',
        width: '150px',
      },
    ]);
    const list = ref();
    const getTableDataFun = async () => {
      const params = {
        connect: getInfo(ICP_CONFIG)?.connect,
        lang: getInfo(ICP_CONFIG)?.lang,
      };
      const data = await useHttp({
        url: '/api/dataperservice/dataPerService/getActionList',
        method: 'post',
        params: params,
      });
      return data;
    };
    const checkStatusAll = ref('');
    const { permissionData } = { ...toRefs(props) };
    const getTableData = () => {
      getTableDataFun().then(result => {
        if (result.code == 200) {
          list.value = result.data;
          checkStatusAll.value = result.data.find(item => item.key === 'ALL').checkStatus;
          nextTick(() => {
            if (permissionData.value?.length) {
              permissionData.value.map(item => {
                list.value?.map(i => {
                  if ((item as any).key === i.key) {
                    i.checkStatus = (item as any).checkStatus;
                  }
                });
              });
              handleListData();
            }
          });
        }
      });
    };
    getTableData();
    const handleChange = (index: number, text: any, key: string) => {
      list.value[index].checkStatus = text;
      checkStatusAll.value = list.value.find(item => item.key === 'ALL').checkStatus;
      list.value = [].concat(list.value as any);
      if (key == 'ALL') {
        if (text != '3') {
          list.value.forEach(item => {
            item.checkStatus = text;
          });
        }
      } else {
        const allIndex = list.value.findIndex(item => item.key == 'ALL');
        let tempData = cloneDeep(list.value);
        tempData.splice(allIndex, 1);
        const result = tempData.some(item => {
          return item.checkStatus != checkStatusAll.value;
        });
        if (result) {
          list.value.map(item => {
            if (item.key == 'ALL') {
              item.checkStatus = '3';
            }
          });
        }
      }
      // 给父级传值
      handleListData();
    };
    // 处理list数据再给后台
    const handleListData = () => {
      const permissionArr = list.value
        .filter(item => item.checkStatus != '3')
        .map(item => {
          const obj = {};
          obj[item.key] = item.checkStatus;
          return obj;
        });
      let permissionArrTemp = [];
      const result = permissionArr.some(item => {
        return item.hasOwnProperty('ALL');
      });
      if (result) {
        const allIndex = permissionArr.findIndex(item => item.ALL);
        permissionArrTemp = permissionArr.splice(allIndex, 1);
      } else {
        permissionArrTemp = permissionArr;
      }
      emit('handlePermissions', JSON.stringify(permissionArrTemp));
    };
    return {
      // 表格配置
      list,
      handleChange,
      columns,
      isStatus,
    };
  },
});
</script>
