<template>
  <!-- 新增编辑 -->
  <common-modal
    :width="800"
    :maskClosable="false"
    :visible="props.visible"
    :confirm-loading="loading"
    :forceRender="true"
    wrapClassName="project-modal"
    :title="isUpdate ? '编辑业务' : '新建业务'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
    @close="updateVisible(false)"
  >
    <ListForm v-model:form="form" ref="modelFormRef" :isUpdate="isUpdate" :iconList="props.iconList"></ListForm>

    <template #footer>
      <a-button class="border-radius grey" @click="updateVisible(false)" type="link">取消</a-button>
      <a-button class="border-radius" type="primary" @click="save">确定</a-button>
    </template>
  </common-modal>
</template>

<script setup name="ListAddEdit">
import { ref, onMounted, computed } from 'vue';
import ListForm from './list-form.vue';
import { message } from 'ant-design-vue';
import { BusinessApi } from '../../api/BusinessApi';
import { CommonApi } from '@/api/CommonApi';
import { getBusinessMaxSort } from '@/utils/common/util';
import { FileApi } from '@/views/system/backend/file/api/FileApi';
import { storeToRefs } from 'pinia';
import { cloneDeep } from 'lodash-es';
import { useUserStore } from '@/store/modules/user';

const props = defineProps({
  visible: Boolean,
  data: Object,
  iconList: Array,
  businessCategoryId: String
});

const emits = defineEmits(['update:visible', 'done']);
// 弹框加载
const loading = ref(false);
// 是否是编辑状态
const isUpdate = ref(false);

const { info } = storeToRefs(useUserStore());

//当前的公司信息
const companyData = computed(() => {
  let userOrgInfoList = info.value.userOrgInfoList;
  let filter = userOrgInfoList.filter(item => item.currentSelectFlag);
  if (filter.length > 0) {
    return filter[0];
  }
});

// 表单数据
const form = ref({
  iconList: [],
  businessIconType: 2,
  businessCategoryId: props.businessCategoryId,
  ownershipDeptIdWrapper: companyData.value?.deptName,
  ownershipDeptId: companyData.value?.orgId,
  businessPermissionList: [],
  newBusinessPermissionList: [],
});
// ref
const modelFormRef = ref(null);

onMounted(async () => {
  if (props.data) {
    isUpdate.value = true;
    getDetail();
  } else {
    form.value.fldSort = await getBusinessMaxSort('DEVOPS_BUSINESS');
    getSystemCode();
    modelFormRef.value.init();
    isUpdate.value = false;
  }
});

// 获取系统编码code
const getSystemCode = async () => {
  const res = await CommonApi.getSystemCode({ systemType: 'BIZ' });
  const { systemCodeShow, systemCode } = res.data;
  form.value.systemCode = systemCode;
  form.value.systemCodeShow = systemCodeShow;
};

// 获取详情
const getDetail = () => {
  BusinessApi.detail({ businessId: props.data.businessId }).then(res => {
    form.value = Object.assign({}, res);
    if (!form.value.businessIconType) form.value.businessIconType = 2;
    form.value.iconList = [];
    if (form.value.businessIconFileId && form.value.businessIconType == 1) {
      setFileList('iconList', res.businessIconFileId);
    }

    if (form.value.businessIcon && form.value.businessIconType == 2) {
      modelFormRef.value.modelIconSet(form.value.businessIcon);
    }

    form.value.newBusinessPermissionList = res?.businessPermissionList || [];
  });
};

// 设置文件列表
const setFileList = async (name, fileId) => {
  let res = await FileApi.getAntdVInfo({ fileId: fileId });
  res.uid = fileId;
  form.value[name] = [res];
};

// 更改弹框状态
const updateVisible = value => {
  emits('update:visible', value);
};

// 点击保存
const save = async () => {
  modelFormRef.value.$refs.formRef.validate().then(async valid => {
    if (valid) {
      // 修改加载框为正在加载
      loading.value = true;

      let result = null;
      let params = cloneDeep(form.value);
      delete params.newBusinessPermissionList;
      params.businessPermissionList = params.businessPermissionList?.map(item => {
        return { ...item, id: null };
      });
      // 执行编辑或修改
      if (isUpdate.value) {
        result = BusinessApi.edit(form.value);
      } else {
        result = BusinessApi.add(form.value);
      }
      result
        .then(async result => {
          // 移除加载框
          loading.value = false;

          // 提示添加成功
          message.success(result.message);
          // 关闭弹框，通过控制visible的值，传递给父组件
          updateVisible(false);

          // 触发父组件done事件
          emits('done');
        })
        .catch(() => {
          loading.value = false;
        });
    }
  });
};
</script>

<style></style>
