<!-- 编辑弹窗 -->
<template>
  <ele-modal
      :width="1000"
      :visible="visible"
      :maskClosable="false"
      :maxable="maxable"
      :title="isUpdate ? '编辑项目' : '添加项目'"
      :body-style="{ paddingBottom: '28px' }"
      @update:visible="updateVisible"
      @ok="save"
  >
    <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
        :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="被审计单位" name="name">
        <SelectCompany v-model:value="form.name" @done="onCompany" />
      </a-form-item>
      <a-form-item label="项目类型" name="type">
        <DictSelect
            dict-code="Type"
            :width="200"
            :show-search="true"
            placeholder="项目类型"
            v-model:value="form.type"
            @done="chooseType"
        />
      </a-form-item>
      <a-form-item label="报告时间" name="expirationTime">
        <a-input
            allow-clear
            style="width: 200px"
            placeholder="请输入报告时间"
            v-model:value="form.expirationTime"
        />
      </a-form-item>
      <a-form-item label="报告编号" name="code">
        <a-input
            allow-clear
            style="width: 400px"
            placeholder="请输入报告编号"
            v-model:value="form.code"
        />
      </a-form-item>

      <!-- 行业库 -->
      <a-form-item label="行业库" name="bizLibIds">
        <a-select
            show-search
            :allow-clear="true"
            optionFilterProp="label"
            v-model:value="form.bizLibIds"
            mode="multiple"
            style="width: 100%"
            placeholder="选择行业库"
            :options="bizLibList"
        ></a-select>
      </a-form-item>

      <!-- 公共库 -->
      <a-form-item label="公共库" name="pubLibIds">
        <a-select
            show-search
            :allow-clear="true"
            optionFilterProp="label"
            v-model:value="form.pubLibIds"
            mode="multiple"
            style="width: 100%"
            placeholder="选择公共库"
            :options="pubLibList"
        ></a-select>
      </a-form-item>

      <a-divider orientation="left" style="margin-top: 50px">项目信息</a-divider>
      <a-form-item label="开票单位/汇款人" name="itemName">
        <a-input
            allow-clear
            style="width: 400px"
            placeholder="请输入项目信息-开票单位/汇款人"
            v-model:value="form.itemName"
        />
      </a-form-item>
      <a-form-item label="所属年度" name="itemYear">
        <a-input-number
            allow-clear
            style="width: 200px"
            placeholder="请输入项目信息-年度"
            v-model:value="form.itemYear"
        />
      </a-form-item>
      <a-form-item label="类型" name="itemType">
        <a-input
            allow-clear
            style="width: 200px"
            placeholder="请输入类型"
            v-model:value="form.itemType"
        />
      </a-form-item>
      <a-form-item label="审计意见" name="itemOpinion">
        <a-input
            allow-clear
            style="width: 200px"
            placeholder="请输入审计意见"
            v-model:value="form.itemOpinion"
        />
      </a-form-item>
      <a-form-item label="年末资产总额(万元)" name="totalAssets">
        <a-input-number
            allow-clear
            style="width: 200px"
            placeholder="请输入年末资产总额(万元)"
            v-model:value="form.totalAssets"
        />
      </a-form-item>
      <a-form-item label="合同金额" name="contractPrice">
        <a-input-number
            allow-clear
            style="width: 200px"
            placeholder="请输入合同金额"
            v-model:value="form.contractPrice"
        />
      </a-form-item>
      <a-form-item label="实收金额" name="payPrice">
        <a-input-number
            allow-clear
            style="width: 200px"
            placeholder="请输入实收金额"
            v-model:value="form.payPrice"
        />
      </a-form-item>
      <a-divider orientation="left" style="margin-top: 50px">到账信息</a-divider>
      <a-form-item label="银行" name="bankName">
        <a-input
            allow-clear
            style="width: 200px"
            placeholder="请输入银行名称"
            v-model:value="form.bankName"
        />
      </a-form-item>
      <a-form-item label="日期" name="bankPayTime">
        <a-input
            allow-clear
            style="width: 200px"
            placeholder="请输入到账日期"
            v-model:value="form.bankPayTime"
        />
      </a-form-item>
      <a-form-item label="金额" name="bankPrice">
        <a-input-number
            allow-clear
            style="width: 200px"
            placeholder="请输入到账金额"
            v-model:value="form.bankPrice"
        />
      </a-form-item>
      <a-divider orientation="left" style="margin-top: 50px">开票信息</a-divider>
      <a-form-item label="日期" name="invoiceTime">
        <a-input
            allow-clear
            style="width: 200px"
            placeholder="请输入开票日期"
            v-model:value="form.invoiceTime"
        />
      </a-form-item>
      <a-form-item label="金额" name="invoicePrice">
        <a-input-number
            allow-clear
            style="width: 200px"
            placeholder="请输入开票金额"
            v-model:value="form.invoicePrice"
        />
      </a-form-item>
      <a-form-item label="类型" name="invoiceType">
        <DictSelect
            dict-code="InvoiceType"
            :width="200"
            :show-search="true"
            placeholder="项目类型"
            v-model:value="form.invoiceType"
        />
      </a-form-item>
      <a-divider orientation="left" style="margin-top: 50px">其他设置</a-divider>
      <a-form-item label="报告份数" name="reportNum">
        <a-input
            allow-clear
            style="width: 200px"
            placeholder="请输入报告份数"
            v-model:value="form.reportNum"
        />
      </a-form-item>
      <a-form-item label="底稿人员" name="draftUserId">
        <a-select
            show-search
            :allow-clear="true"
            optionFilterProp="label"
            v-model:value="form.draftUserId"
            mode="tags"
            style="width: 100%"
            placeholder="选择底稿人员"
            :options="userList"
            @search="handleSearch"
            @change="handleDraftUserId"
        ></a-select>
      </a-form-item>
      <a-form-item label="参与成员" name="userIds" extra="配置项目权限->参与成员可见">
        <a-select
            show-search
            :allow-clear="true"
            optionFilterProp="label"
            v-model:value="form.userIds"
            mode="tags"
            style="width: 100%"
            placeholder="选择参与成员"
            :options="userList"
            @change="handleUsers"
        ></a-select>
      </a-form-item>
      <a-form-item label="签字注会" name="signUserId">
        <a-select
            show-search
            :allow-clear="true"
            optionFilterProp="label"
            v-model:value="form.signUserId"
            mode="tags"
            style="width: 100%"
            placeholder="选择参与成员"
            :options="userList"
            @change="handleSignUser"
        ></a-select>
      </a-form-item>
      <a-form-item label="展业人员" name="saleUserId">
        <a-select
            show-search
            :allow-clear="true"
            optionFilterProp="label"
            v-model:value="form.saleUserId"
            mode="tags"
            style="width: 100%"
            placeholder="选择参与成员"
            :options="userList"
            @change="handleSaleUser"
        ></a-select>
      </a-form-item>
      <a-form-item label="电子底稿完成情况" name="electron">
        <a-space direction="vertical">
          <a-radio-group v-model:value="form.electron">
            <a-radio :value="1">未完成</a-radio>
            <a-radio :value="0">已完成</a-radio>
          </a-radio-group>
        </a-space>
      </a-form-item>
      <a-form-item label="纸质底稿完成情况" name="paper">
        <a-space direction="vertical">
          <a-radio-group v-model:value="form.paper">
            <a-radio :value="1">未完成</a-radio>
            <a-radio :value="0">已完成</a-radio>
          </a-radio-group>
        </a-space>
      </a-form-item>
      <a-form-item label="报告完成状态" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="1">未完成</a-radio>
          <a-radio :value="0">已完成</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="排序" name="sortNumber">
        <a-input-number
            :min="0"
            :max="9999"
            placeholder="请输入排序号"
            v-model:value="form.sortNumber"
        />
      </a-form-item>
      <a-form-item label="备注" name="comments">
        <a-textarea
            :rows="4"
            :maxlength="200"
            placeholder="请输入描述"
            v-model:value="form.comments"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
import {ref, reactive, watch} from 'vue';
import {Form, message} from 'ant-design-vue';
import {assignObject, uuid} from 'ele-admin-pro';
import {addPwlProject, updatePwlProject} from '@/api/pwl/pwlProject';
import {PwlProject} from '@/api/pwl/pwlProject/model';
import {useThemeStore} from '@/store/modules/theme';
import {storeToRefs} from 'pinia';
import {ItemType} from 'ele-admin-pro/es/ele-image-upload/types';
import {FormInstance} from 'ant-design-vue/es/form';
import DictSelect from "@/components/DictSelect/index.vue";
import {DictData} from "@/api/system/dict-data/model";
import {pageUsers} from "@/api/system/user";
import {User} from "@/api/system/user/model";
import {hasRole} from "@/utils/permission";
import SelectCompany from "@/components/SelectCompany/index.vue";
import {Company} from "@/api/system/company/model";
import {OaCompany} from "@/api/oa/oaCompany/model";
import {listPwlProjectLibrary} from '@/api/pwl/pwlProjectLibrary';


// 是否是修改
const isUpdate = ref(false);
const useForm = Form.useForm;
// 是否开启响应式布局
const themeStore = useThemeStore();
const {styleResponsive} = storeToRefs(themeStore);

// 资料库响应式数据
const bizLibList = ref<any[]>([]);
const pubLibList = ref<any[]>([]);
// 存储完整的资料库数据，用于查找名称
const allLibraries = ref<any[]>([]);

const props = defineProps<{
  // 弹窗是否打开
  visible: boolean;
  // 修改回显的数据
  data?: PwlProject | null;
}>();

const emit = defineEmits<{
  (e: 'done'): void;
  (e: 'update:visible', visible: boolean): void;
}>();

// 提交状态
const loading = ref(false);
// 是否显示最大化切换按钮
const maxable = ref(true);
// 表格选中数据
const formRef = ref<FormInstance | null>(null);
const images = ref<ItemType[]>([]);
const userList = ref<User[]>([]);
const draftUser = ref<any[]>([]);
const users = ref<any[]>([]);
const signUser = ref<any[]>([]);
const saleUser = ref<any[]>([]);
const keywords = ref<string>();

// 用户信息
const form = reactive<PwlProject>({
  id: undefined,
  name: undefined,
  code: undefined,
  parentId: undefined,
  type: undefined,
  image: undefined,
  qrcode: undefined,
  url: undefined,
  images: undefined,
  files: undefined,
  content: undefined,
  totalAssets: undefined,
  contractPrice: undefined,
  payPrice: undefined,
  price: undefined,
  recommend: undefined,
  expirationTime: undefined,
  itemName: undefined,
  itemYear: undefined,
  itemType: undefined,
  itemOpinion: undefined,
  bankName: undefined,
  bankPayTime: undefined,
  bankPrice: undefined,
  invoiceType: undefined,
  invoiceTime: undefined,
  invoicePrice: undefined,
  reportNum: undefined,
  draftUserId: [],
  draftUser: [],
  userIds: [],
  users: [],
  signUserId: [],
  signUser: [],
  saleUserId: [],
  saleUser: [],
  bizLibIds: [], // 修改为bizLibIds
  bizLibName: [],
  pubLibIds: [], // 修改为pubLibIds
  pubLibName: [],
  libraryIds: undefined, // 新增libraryIds字段
  comments: undefined,
  electron: undefined,
  paper: undefined,
  status: undefined,
  deleted: undefined,
  userId: undefined,
  tenantId: undefined,
  createTime: undefined,
  updateTime: undefined,
  sortNumber: 100,
});

/* 更新visible */
const updateVisible = (value: boolean) => {
  emit('update:visible', value);
};

// 表单验证规则
const rules = reactive({
  type: [
    {
      required: true,
      type: 'string',
      message: '请选择项目类型',
      trigger: 'change'
    }
  ],
  name: [
    {
      required: true,
      type: 'string',
      message: '请填写项目名称',
      trigger: 'blur'
    }
  ],
  draftUserId: [
    {
      required: true,
      type: 'array',
      message: '请选择底稿人员',
      trigger: 'change'
    }
  ],
  userIds: [
    {
      required: true,
      type: 'array',
      message: '请选择参与成员',
      trigger: 'change'
    }
  ],
  saleUserId:[
    {
      required: true,
      type: 'array',
      message: '请选择展业人员',
      trigger: 'change'
    }
  ],
  electron: [
    {
      required: true,
      type: 'number',
      message: '电子底稿是否已完成',
      trigger: 'change'
    }
  ],
  paper: [
    {
      required: true,
      type: 'number',
      message: '纸质底稿是否已完成',
      trigger: 'change'
    }
  ],
  status: [
    {
      required: true,
      type: 'number',
      message: '请选择项目状态',
      trigger: 'change'
    }
  ]
});

const chooseType = (data: DictData) => {
  console.log(data);
  form.type = data.dictDataName;
}
// const chooseImage = (data: FileRecord) => {
//   images.value.push({
//     uid: data.id,
//     url: data.path,
//     status: 'done'
//   });
//   form.image = data.path;
// };
//
// const onDeleteItem = (index: number) => {
//   images.value.splice(index, 1);
//   form.image = '';
// };


const onCompany = (item: OaCompany) => {
  console.log('选择的公司:', item);
  form.name = item.companyName;
  form.kbId = item.kbId;
  console.log('设置后的form.name:', form.name);
};

const handleSearch = (item) => {
  keywords.value = item
  fetchUsers();
}

const handleDraftUserId = (userId: number, item: User[]) => {
  draftUser.value = [];
  item.map(d => {
    draftUser.value.push(d.realName);
  });
  console.log(userId)
}

const handleUsers = (userId: number, item: User[]) => {
  users.value = [];
  item.map(d => {
    users.value.push(d.realName);
  });
  console.log(userId)
}
const handleSignUser = (userId: number, item: User[]) => {
  signUser.value = [];
  item.map(d => {
    signUser.value.push(d.realName);
  });
  console.log(userId)
}
const handleSaleUser = (userId: number, item: User[]) => {
  saleUser.value = [];
  item.map(d => {
    saleUser.value.push(d.realName);
  });
  console.log(userId)
}

// 获取用户列表
const fetchUsers = () => {
  pageUsers({keywords: keywords.value,limit: 100}).then(res => {
    userList.value = res?.list.map(d => {
      d.label = d.realName;
      d.value = d.userId;
      return d;
    }) || [];
  })
};

// 获取资料库列表
const fetchLibraries = () => {
  return listPwlProjectLibrary().then(res => {
    allLibraries.value = res;

    // 过滤行业库 (type='biz')
    bizLibList.value = res
        .filter(item => item.type === 'biz')
        .map(item => ({
          label: item.name,
          value: String(item.id)  // 将 ID 转换为字符串
        }));

    // 过滤公共库 (type='pub')
    pubLibList.value = res
        .filter(item => item.type === 'pub')
        .map(item => ({
          label: item.name,
          value: String(item.id)  // 将 ID 转换为字符串
        }));

    return res;
  });
};

// 根据ID获取资料库名称
const getLibraryNamesByIds = (ids: string[]) => {
  return ids.map(id => {
    const library = allLibraries.value.find(lib => lib.id == id);
    return library ? library.name : '';
  }).filter(name => name !== '');
};

const {resetFields} = useForm(form, rules);

/* 保存编辑 */
const save = () => {
  if (!formRef.value) {
    return;
  }
  formRef.value
      .validate()
      .then(() => {
        loading.value = true;

        // 合并行业库和公共库的ID到libraryIds
        const allLibraryIds = [
          ...(form.bizLibIds || []),
          ...(form.pubLibIds || [])
        ]

        const formData = {
          ...form,
          draftUserId: JSON.stringify(form.draftUserId),
          draftUser: JSON.stringify(Array.from(new Set(draftUser.value))),
          userIds: JSON.stringify(form.userIds),
          users: JSON.stringify(Array.from(new Set(users.value))),
          signUserId: JSON.stringify(form.signUserId),
          signUser: JSON.stringify(Array.from(new Set(signUser.value))),
          saleUserId: JSON.stringify(form.saleUserId),
          saleUser: JSON.stringify(Array.from(new Set(saleUser.value))),
          libraryIds: allLibraryIds.join(','), // 保存为逗号分隔的字符串
        };

        if (!hasRole('superAdmin')) {
          form.payPrice = undefined;
        }
        if (!hasRole('admin')) {
          form.contractPrice = undefined;
          form.bankName = undefined;
          form.bankPayTime = undefined;
          form.bankPrice = undefined;
          form.invoiceType = undefined;
          form.invoiceTime = undefined;
          form.invoicePrice = undefined;
        }
        console.log(formData);
        const saveOrUpdate = isUpdate.value ? updatePwlProject : addPwlProject;
        saveOrUpdate(formData)
            .then((msg) => {
              loading.value = false;
              message.success(msg);
              updateVisible(false);
              emit('done');
            })
            .catch((e) => {
              loading.value = false;
              message.error(e.message);
            });
      })
      .catch(() => {
      });
};

// 设置资料库回显
const setLibraryEcho = () => {
  if (props.data?.libraryIds) {
    // 如果是字符串，按逗号分割成数组
    if (typeof props.data.libraryIds === 'string') {
      const libraryIdsArray = props.data.libraryIds.split(',').filter(id => id.trim() !== '');

      // 清空当前的选择
      form.bizLibIds = [];
      form.pubLibIds = [];

      // 根据资料库类型分别设置回显
      libraryIdsArray.forEach(id => {
        // 检查是否在行业库列表中
        const isBizLib = bizLibList.value.some(lib => lib.value === String(id));  // 转换为字符串比较
        // 检查是否在公共库列表中
        const isPubLib = pubLibList.value.some(lib => lib.value === String(id));  // 转换为字符串比较

        if (isBizLib) {
          form.bizLibIds.push(String(id));  // 确保存储为字符串
        }
        if (isPubLib) {
          form.pubLibIds.push(String(id));  // 确保存储为字符串
        }
      });
    } else {
      // 如果是数组，直接使用相同的逻辑
      form.bizLibIds = [];
      form.pubLibIds = [];

      props.data.libraryIds.forEach(id => {
        const isBizLib = bizLibList.value.some(lib => lib.value === String(id));
        const isPubLib = pubLibList.value.some(lib => lib.value === String(id));

        if (isBizLib) {
          form.bizLibIds.push(String(id));
        }
        if (isPubLib) {
          form.pubLibIds.push(String(id));
        }
      });
    }
  } else {
    form.bizLibIds = [];
    form.pubLibIds = [];
  }
};

watch(
    () => props.visible,
    async (visible) => {
      if (visible) {
        fetchUsers();

        // 等待资料库列表加载完成后再设置回显
        await fetchLibraries();

        images.value = [];
        if (props.data) {
          assignObject(form, props.data);
          if (props.data.image) {
            images.value.push({
              uid: uuid(),
              url: props.data.image,
              status: 'done'
            })
          }

          // 处理底稿人员
          if (props.data.draftUserId) {
            form.draftUserId = JSON.parse(props.data.draftUserId);
          } else {
            form.draftUserId = [];
          }
          if (props.data.draftUser) {
            const arr = JSON.parse(props.data.draftUser) || [];
            arr.map(d => {
              draftUser.value.push(d);
            })
          } else {
            draftUser.value = [];
          }

          // 处理参与成员
          if (props.data.userIds) {
            form.userIds = JSON.parse(props.data.userIds) || [];
          } else {
            form.userIds = [];
          }
          if (props.data.users) {
            const arr = JSON.parse(props.data.users) || [];
            arr.map(d => {
              users.value.push(d);
            })
          } else {
            users.value = [];
          }

          // 处理签字注会
          if (props.data.signUserId) {
            form.signUserId = JSON.parse(props.data.signUserId) || [];
          } else {
            form.signUserId = [];
          }
          if (props.data.signUser) {
            const arr = JSON.parse(props.data.signUser) || [];
            arr.map(d => {
              signUser.value.push(d);
            })
          } else {
            signUser.value = [];
          }

          // 处理展业人员
          if (props.data.saleUserId) {
            form.saleUserId = JSON.parse(props.data.saleUserId) || [];
          } else {
            form.saleUserId = [];
          }
          if (props.data.saleUser) {
            const arr = JSON.parse(props.data.saleUser) || [];
            arr.map(d => {
              saleUser.value.push(d);
            })
          } else {
            saleUser.value = [];
          }

          // 设置资料库回显
          setLibraryEcho();

          isUpdate.value = true;
        } else {
          isUpdate.value = false;
          // 新增时清空资料库选择
          form.bizLibIds = [];
          form.pubLibIds = [];
        }
      } else {
        resetFields();
      }
    },
    {immediate: true}
);
</script>
