<!-- 编辑弹窗 -->
<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="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="name">
        <a-input
          allow-clear
          style="width: 400px"
          placeholder="请输入审计单位"
          v-model:value="form.name"
        />
      </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-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";

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

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: [],
  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 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 {resetFields} = useForm(form, rules);

/* 保存编辑 */
const save = () => {
  if (!formRef.value) {
    return;
  }
  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      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))),
      };
      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(() => {
    });
};

watch(
  () => props.visible,
  (visible) => {
    fetchUsers();
    if (visible) {
      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 = [];
        }
        // 清空所有用户数组，避免数据累积
        draftUser.value = [];
        users.value = [];
        signUser.value = [];
        saleUser.value = [];

        if (props.data.draftUser) {
          const arr = JSON.parse(props.data.draftUser) || [];
          draftUser.value = [...arr]; // 直接赋值，避免push累积
        }

        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) || [];
          users.value = [...arr]; // 直接赋值，避免push累积
        }

        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) || [];
          signUser.value = [...arr]; // 直接赋值，避免push累积
        }

        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) || [];
          saleUser.value = [...arr]; // 直接赋值，避免push累积
        }
        isUpdate.value = true;
      } else {
        isUpdate.value = false;
        // 新增时也要清空用户数组
        draftUser.value = [];
        users.value = [];
        signUser.value = [];
        saleUser.value = [];
      }
    } else {
      resetFields();
      // 弹窗关闭时清空所有用户数组
      draftUser.value = [];
      users.value = [];
      signUser.value = [];
      saleUser.value = [];
    }
  },
  {immediate: true}
);
</script>
