<template>
  <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
    <a-tabs v-model:activeKey="activeKey" class="devops-tabs" style="margin-bottom: 16px">
      <a-tab-pane key="1" tab="基本信息" />
      <a-tab-pane key="2" tab="权限配置" />
    </a-tabs>
    <a-row :gutter="20" v-show="activeKey == '1'">
      <a-col :span="24">
        <a-row :gutter="20">
          <a-col :span="24">
            <a-row :gutter="20">
              <a-col :span="19">
                <a-form-item label="业务名称:" name="businessName">
                  <a-input v-model:value="form.businessName" allow-clear placeholder="请输入业务名称" />
                </a-form-item>
                <a-form-item label="业务编码:" name="businessCode">
                  <a-input v-model:value="form.businessCode" allow-clear placeholder="请输入业务编码" />
                </a-form-item>
              </a-col>
              <a-col :span="5" class="pick">
                <a-form-item label="图标:">
                  <div class="modular-icon" @click="imgClick">
                    <img :src="activeIconSrc" style="width: 100%; height: 100%" />
                  </div>
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-col>
      <a-col :span="19" class="remark">
        <a-form-item label="系统编码:" name="systemCodeShow">
          <a-input v-model:value="form.systemCodeShow" allow-clear placeholder="请输入系统编码" disabled />
        </a-form-item>
      </a-col>
      <a-col :span="5">
        <a-form-item label="排序:" name="fldSort">
          <a-input-number
            v-model:value="form.fldSort"
            :min="0"
            style="width: 100%"
            placeholder="请输入排序"
            allow-clear
            autocomplete="off"
          />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="表格所属部门:" name="ownershipDeptIdWrapper">
          <a-input v-model:value="form.ownershipDeptIdWrapper" readonly placeholder="请选择表格所属部门" @click="deptClick"></a-input>
        </a-form-item>
      </a-col>
    </a-row>

    <a-row :gutter="20" v-show="activeKey == '2'">
      <a-col :span="24" style="height: 400px;">
        <common-table
          :columns="columns"
          :showToolTotal="false"
          size="small"
          :isPage="false"
          :rowSelection="false"
          :scroll="{}"
          :dataSource="form.newBusinessPermissionList"
        >
          <template #toolLeft>
            <a-tabs v-model:activeKey="currentLinkType" class="devops-tabs report-t" @change="getBusinessPermissionList">
              <a-tab-pane :key="0" tab="全部" />
              <a-tab-pane :key="10" tab="机构" />
              <a-tab-pane :key="20" tab="人员" />
            </a-tabs>
          </template>
          <template #toolRight>
            <a @click="addPer" v-if="currentLinkType != 0">新增</a>
          </template>
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key == 'index'">{{ index + 1 }}</template>
            <template v-if="column.dataIndex == 'linkBusinessName'">
              <a-input
                v-model:value="record.linkBusinessName"
                @click="linkBusinessNameClick(record)"
                placeholder="请选择"
                :bordered="false"
                :disabled="currentLinkType == 0 ? true : false"
              ></a-input>
            </template>
            <template v-if="column.dataIndex == 'linkType'">
              <a-select
                v-model:value="record.linkType"
                placeholder="请选择类型"
                style="width: 100%"
                :bordered="false"
                :showArrow="currentLinkType == 0 ? false : true"
                :disabled="currentLinkType == 0 ? true : false"
                @change="valueChange(record, 'linkType')"
              >
                <a-select-option :value="10" v-if="[0, 10].includes(currentLinkType)">机构</a-select-option>
                <a-select-option :value="20" v-if="[0, 20].includes(currentLinkType)">人员</a-select-option>
              </a-select>
            </template>
            <template v-if="column.dataIndex == 'scopeType'">
              <a-select
                v-model:value="record.scopeType"
                placeholder="请选择范围"
                style="width: 100%"
                :bordered="false"
                :showArrow="currentLinkType == 0 ? false : true"
                :disabled="currentLinkType == 0 ? true : false"
                @change="valueChange(record, 'scopeType')"
              >
                <a-select-option :value="1">指定范围</a-select-option>
                <a-select-option :value="2" v-if="record.linkType == 10">指定部门及以下</a-select-option>
              </a-select>
            </template>
            <template v-if="column.dataIndex == 'operateType'">
              <a-select
                v-model:value="record.operateType"
                placeholder="请选择操作权限"
                style="width: 100%"
                :bordered="false"
                :showArrow="currentLinkType == 0 ? false : true"
                :disabled="currentLinkType == 0 ? true : false"
                @change="valueChange(record, 'operateType')"
              >
                <a-select-option :value="1">仅填报</a-select-option>
                <a-select-option :value="2">仅管理</a-select-option>
                <a-select-option :value="3">填报及管理</a-select-option>
              </a-select>
            </template>
            <template v-if="column.dataIndex == 'action'">
              <icon-font
                iconClass="icon-opt-shanchu"
                font-size="24px"
                title="删除"
                color="#60666b"
                @click="remove(record)"
                v-if="currentLinkType != 0"
              ></icon-font>
            </template>
          </template>
        </common-table>
      </a-col>
    </a-row>

    <a-modal :visible="visibleIcon" width="620px" title="选择图标" @ok="iconOk" @cancel="visibleIcon = false">
      <div class="type-icon">
        <a-radio-group v-model:value="props.form.businessIconType">
          <a-radio :value="1">自定义上传</a-radio>
          <a-radio :value="2">选择图片</a-radio>
        </a-radio-group>
      </div>
      <div v-if="props.form.businessIconType == 2">
        <img
          v-for="(icon, index) in iconList"
          :key="index"
          :src="icon.url"
          class="flow-icon-item"
          :class="{ active: selectedIcon === icon.name_suffix }"
          @click="selectedIconClick(icon)"
        />
      </div>
      <div v-if="props.form.businessIconType == 1">
        <a-upload
          name="file"
          :multiple="false"
          v-model:file-list="selectIconList"
          :default-file-list="selectIconList"
          :maxCount="1"
          :action="iconData.fileUploadUrl"
          list-type="picture-card"
          :headers="iconData.headers"
          :before-upload="beforeUpload"
          accept=".jpeg,.jpg,.png,.tif,.jfif,.webp,.pjp,.apng,.pjpeg,.avif,.ico,.tiff,.bmp,.xbm,.jxl,.jpeg,.svgz,.gif,.svg"
          @preview="handlePreviewPhoto"
          @download="downloadPhoto"
          @change="info => handleFileChange(info, 'selectIconList')"
          :showUploadList="{
            showDownloadIcon: true
          }"
        >
          <plus-outlined style="font-size: 28px; font-weight: 200" v-if="selectIconList.length == 0" />
        </a-upload>
      </div>
    </a-modal>

    <!-- 图标预览弹框 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>

    <Selection
      v-model:visible="visibleSelection"
      v-if="visibleSelection"
      :data="selectedData"
      :showTab="['dept']"
      :changeHeight="true"
      title="请选择组织"
      :isRadio="true"
      @done="closeSelection"
    ></Selection>

    <!-- 选择弹框 -->
    <Selection
      v-model:visible="showSelect"
      v-if="showSelect"
      :data="selectedData"
      :showTab="showTab"
      :title="'选择'"
      :isRadio="isRadio"
      @done="closeFlowPick"
    ></Selection>
  </a-form>
</template>

<script setup name="ListForm">
import { reactive, ref, computed } from 'vue';
import { getToken } from '@/utils/token-util';
import { API_BASE_PREFIX } from '@/config/setting';
import { FileApi, FileUploadUrl as fileUploadUrlPrefix } from '@/views/system/backend/file/api/FileApi';
import { message, Upload } from 'ant-design-vue/es';
import { deepClone, getUUID } from '@/utils/common/util';
import { cloneDeep } from 'lodash-es';

const props = defineProps({
  // 表单数据
  form: Object,
  isUpdate: Boolean,
  iconList: Array
});

// 图标上传预览地址
const iconData = reactive({
  // 上传文件的url
  fileUploadUrl: `${API_BASE_PREFIX}${fileUploadUrlPrefix}?secretFlag=N`,
  filePreviewUrl: `${API_BASE_PREFIX}/sysFileInfo/public/preview?fileId=`,
  // 上传文件时候要带header
  headers: {
    Authorization: getToken()
  }
});

const selectIconList = ref([]);

// 是否展示图片预览
const previewVisible = ref(false);
// 图片地址
const previewImage = ref(null);

const visibleIcon = ref(false);

// 当前激活图标
const activeIcon = ref(null);
// 当前选中图标
const selectedIcon = ref(null);

// 是否显示弹框
const visibleSelection = ref(false);

// 选择总数据
const selectedData = ref({
  selectOrgList: [],
  selectUserList: [],
  selectOrgList: []
});

const showSelect = ref(false);

// 显示的tab
const showTab = ref(['user']);

const isRadio = ref(true);

const columns = ref([
  {
    key: 'index',
    title: '序号',
    width: 60,
    align: 'center',
    hideInSetting: true
  },
  {
    title: '名称',
    width: 100,
    dataIndex: 'linkBusinessName'
  },
  {
    title: '类型',
    width: 70,
    dataIndex: 'linkType'
  },
  {
    title: '范围',
    width: 130,
    dataIndex: 'scopeType'
  },
  {
    title: '操作权限',
    width: 110,
    dataIndex: 'operateType'
  },
  {
    title: '操作',
    width: 60,
    align: 'center',
    dataIndex: 'action'
  }
]);

const currentLinkType = ref(0);

const current = ref(null);

// 验证规则
const rules = reactive({
  businessName: [{ required: true, message: '请输入业务名称', type: 'string', trigger: 'blur' }],
  businessCode: [{ required: true, message: '请输入业务编码', type: 'string', trigger: 'blur' }],
  systemCodeShow: [{ required: true, message: '请输入系统编码', type: 'string', trigger: 'blur' }],
  fldSort: [{ required: true, message: '请输入排序', type: 'number', trigger: 'blur' }],
  ownershipDeptIdWrapper: [{ required: true, message: '请选择表格所属部门', type: 'string', trigger: 'blur' }]
});

const activeKey = ref('1');

/**
 * 图标
 */
const activeIconSrc = computed(() => {
  const icon = props.iconList.find(t => t.name_suffix == activeIcon.value);
  if (props.form.businessIconType == 2) {
    return icon ? icon.url : '';
  } else {
    let fileId = '';
    if (props.form.iconList?.length > 0) {
      fileId = props.form.iconList[0]?.response?.data?.fileId
        ? props.form.iconList[0]?.response?.data?.fileId
        : props.form.iconList[0]?.uid;
    }
    return iconData.filePreviewUrl + fileId;
  }
});

const imgClick = () => {
  selectIconList.value = deepClone(props.form.iconList);
  visibleIcon.value = true;
};

// 图标点击
const selectedIconClick = icon => {
  selectedIcon.value = icon.name_suffix;
  iconOk();
};

//   关闭选择图标弹框
const iconOk = () => {
  if (props.form.businessIconType == 1) {
    if (selectIconList.value.length == 0) return message.warning('请上传一个图标');
    props.form.iconList = deepClone(selectIconList.value);
  } else {
    activeIcon.value = selectedIcon.value;
    props.form.businessIcon = selectedIcon.value;
    props.form.businessIconFileId = '';
    props.form.iconList = [];
    selectIconList.value = [];
  }
  visibleIcon.value = false;
};

//上传之前的回调
const beforeUpload = file => {
  const isJpgOrPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/jpg' ||
    file.type === 'image/png' ||
    file.type === 'image/tif' ||
    file.type === 'image/jfif' ||
    file.type === 'image/webp' ||
    file.type === 'image/pjp' ||
    file.type === 'image/apng' ||
    file.type === 'image/pjpeg' ||
    file.type === 'image/avif' ||
    file.type === 'image/ico' ||
    file.type === 'image/tiff' ||
    file.type === 'image/bmp' ||
    file.type === 'image/xbm' ||
    file.type === 'image/jxl' ||
    file.type === 'image/svgz' ||
    file.type === 'image/gif' ||
    file.type === 'image/svg';
  if (!isJpgOrPng) {
    message.error('只能上传图片!');
    return Upload.LIST_IGNORE; //阻止列表展现
  }
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    message.error('图片大小不能超过5MB!');
  }
  return isJpgOrPng && isLt5M;
};

// 上传成功
const handleFileChange = (info, list) => {
  if (info.file.status === 'done') {
    // 设置临时fileList的值
    props.form[list] = [info.file];
    props.form.businessIconFileId = info.file.response.data.fileId;
    props.form.businessIcon = '';
    activeIcon.value = '';
    selectedIcon.value = '';
    // 将文件属性名和文件编码存入数组中
    message.success(`${info.file.name} 图片上传成功`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 图片上传失败`);
  }
};

// 点击预览图片
const handlePreviewPhoto = async file => {
  previewImage.value = file.url || file.preview || file.thumbUrl;
  previewVisible.value = true;
};

//下载图片
const downloadPhoto = file => {
  let id = file.response ? file.response.data.fileId : file.uid;
  FileApi.download({ token: getToken(), fileId: id });
};

const init = () => {
  activeIcon.value = props.iconList[0].name_suffix;
  selectedIcon.value = props.iconList[0].name_suffix;
  props.form.businessIcon = props.iconList[0].name_suffix;
};

const modelIconSet = value => {
  activeIcon.value = value;
  selectedIcon.value = value;
};

const deptClick = () => {
  const { ownershipDeptIdWrapper, ownershipDeptId } = props.form;
  if (ownershipDeptIdWrapper && ownershipDeptId) {
    selectedData.value.selectOrgList = [{ bizId: ownershipDeptId, name: ownershipDeptIdWrapper }];
  }
  visibleSelection.value = true;
};

const closeSelection = data => {
  const { bizId, name } = data.selectOrgList[0] || { bizId: '', name: '' };
  props.form.ownershipDeptId = bizId;
  props.form.ownershipDeptIdWrapper = name;
};

const addPer = () => {
  isRadio.value = false;
  if (currentLinkType.value == 10) {
    selectedData.value.selectOrgList = [];
  } else {
    selectedData.value.selectUserList = [];
  }
  showTab.value = currentLinkType.value == 10 ? ['dept'] : ['user'];
  showSelect.value = true;
};

const getBusinessPermissionList = () => {
  if (currentLinkType.value == 0) {
    props.form.newBusinessPermissionList = cloneDeep(props.form.businessPermissionList);
  } else if (currentLinkType.value == 10) {
    props.form.newBusinessPermissionList = props.form.businessPermissionList.filter(item => item.linkType == 10);
  } else if (currentLinkType.value == 20) {
    props.form.newBusinessPermissionList = props.form.businessPermissionList.filter(item => item.linkType == 20);
  }
};

const remove = record => {
  const index = props.form.businessPermissionList.findIndex(item => item.id == record.id);
  props.form.businessPermissionList.splice(index, 1);
  getBusinessPermissionList();
};

const valueChange = (record, fieldType) => {
  if (fieldType == 'linkType') {
    record.linkBusinessId = '';
    record.linkBusinessName = '';
    record.scopeType = 1;
  }
  const index = props.form.businessPermissionList.findIndex(item => item.id == record.id);
  props.form.businessPermissionList[index] = record;
};

const linkBusinessNameClick = record => {
  isRadio.value = true;
  selectType.value = 'table';
  current.value = record;
  const { linkBusinessName, linkBusinessId, linkType } = record;
  showTab.value = linkType == 10 ? ['dept'] : ['user'];
  if (linkBusinessName && linkBusinessId) {
    if (linkType == 10) {
      selectedData.value.selectOrgList = [{ bizId: linkBusinessId, name: linkBusinessName }];
    } else {
      selectedData.value.selectUserList = [{ bizId: linkBusinessId, name: linkBusinessName }];
    }
  }
  showSelect.value = true;
};

// 关闭选择弹框
const closeFlowPick = data => {
  if (isRadio.value) {
    if (selectType.value == 'table') {
      const index = props.form.businessPermissionList.findIndex(item => item.id == current.value.id);
      const { selectOrgList, selectUserList } = data;
      const selectedList = current.value.linkType === 10 ? selectOrgList : selectUserList;
      const { bizId, name } = selectedList[0] || { bizId: '', name: '' };
      props.form.businessPermissionList[index].linkBusinessId = bizId;
      props.form.businessPermissionList[index].linkBusinessName = name;
      getBusinessPermissionList();
    } else if (selectType.value == 'deptName') {
      const { bizId, name } = data.selectOrgList[0] || { bizId: '', name: '' };
      props.form.businessFilingConfig.ownershipDeptId = bizId;
      props.form.businessFilingConfig.ownershipDeptIdWrapper = name;
    }
  } else {
    const list = currentLinkType.value == 10 ? data.selectOrgList : data.selectUserList;
    list.forEach(item => {
      if (!props.form.businessPermissionList.find(b => b.linkBusinessId == item.bizId)) {
        let obj = {
          id: getUUID(18),
          linkBusinessId: item.bizId,
          linkBusinessName: item.name,
          linkType: currentLinkType.value == 20 ? 20 : 10,
          operateType: 1,
          scopeType: 1
        };
        props.form.businessPermissionList.push(obj);
      }
    });

    getBusinessPermissionList();
  }
};

defineExpose({
  init,
  modelIconSet
});
</script>

<style scoped lang="less">
:deep(.report-t) {
  .ant-tabs-nav {
    margin: 0;
  }
}
.modular-icon {
  width: 125px;
  height: 125px;
  border: 1px solid #eee;
  border-radius: 6px;
  vertical-align: middle;
  img {
    cursor: pointer;
  }
}
:deep(.ant-form-item-label > label) {
  font-size: 16px !important;
}
:deep(.ant-input) {
  font-size: 16px !important;
}
.remark {
  :deep(.ant-form-item) {
    margin-bottom: 0px;
  }
}
.flow-icon-item {
  width: 40px;
  height: 40px;
  margin: 6px;
  position: relative;
  cursor: pointer;

  &.active {
    opacity: 1;
    -webkit-filter: grayscale(100%);
    -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%);
    -o-filter: grayscale(100%);
    filter: grayscale(100%);
    filter: gray;
  }

  &:hover {
    opacity: 1;
  }
}
.type-icon {
  margin-bottom: 10px;
}
</style>
