<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="750"
    :visible="visible"
    :confirm-loading="loading"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑客户' : '添加客户'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
      <a-form
        :label-col="{ md: { span: 6 }, sm: { span: 20 }, xs: { span: 24 } }"
        :wrapper-col="{ md: { span: 24 }, sm: { span: 20 }, xs: { span: 24 } }"
      >
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="客户名称" v-bind="validateInfos.name">
              <a-input
                allow-clear
                :maxlength="30"
                placeholder="请输入客户名称"
                v-model:value="form.name"
                @blur="
                  validate('customerName', { trigger: 'blur' }).catch(() => {})
                "
              />
            </a-form-item>
            <a-form-item label="客户标识" v-bind="validateInfos.creditCode">
              <a-input
                allow-clear
                :maxlength="20"
                placeholder="请输入社会统一信用代码"
                v-model:value="form.creditCode"
              />
            </a-form-item>
            <a-form-item label="联系人" v-bind="validateInfos.customerContacts">
              <a-input
                allow-clear
                :maxlength="20"
                placeholder="请填写联系人"
                v-model:value="form.contact"
              />
            </a-form-item>
            <a-form-item label="手机号码" v-bind="validateInfos.phone">
              <a-input
                allow-clear
                :maxlength="20"
                placeholder="请填写联系人手机号码"
                v-model:value="form.telPhone"
              />
            </a-form-item>
            <a-form-item label="头像" v-bind="validateInfos.customerAvatar">
              <ele-image-upload
                v-model:value="images"
                :item-style="{ width: '90px', height: '90px' }"
                :limit="1"
                @upload="onUpload"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="客户全称" v-bind="validateInfos.customerFullName">
              <a-input
                allow-clear
                :maxlength="30"
                placeholder="请输入客户全称"
                v-model:value="form.fullName"
                @blur="
                  validate('customerFullName', { trigger: 'blur' }).catch(() => {})
                "
              />
            </a-form-item>
            <a-form-item
              label="联系地址"
              v-bind="validateInfos.customerAddress"
            >
              <a-input
                allow-clear
                placeholder="请填写联系地址"
                v-model:value="form.address"
              />
            </a-form-item>
            <a-form-item label="公司座机" v-bind="validateInfos.customerPhone">
              <a-input
                allow-clear
                :maxlength="20"
                placeholder="请填写公司座机电话"
                v-model:value="form.phone"
              />
            </a-form-item>
            <a-form-item label="排序" v-bind="validateInfos.sortNumber">
              <a-input
                allow-clear
                :maxlength="20"
                placeholder="排序"
                v-model:value="form.sortNumber"
              />
            </a-form-item>
            <a-form-item label="备注" v-bind="validateInfos.comments">
              <a-textarea
                :rows="4"
                :maxlength="200"
                placeholder="请输入备注"
                v-model:value="form.remark"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
import {ref, reactive, watch, computed} from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import { addCustomer, updateCustomer } from '@/api/oa/customer';
  import type { Customer } from '@/api/oa/customer/model';
  import { createCode } from '@/utils/common';
  import { uploadFile } from '@/api/system/file';
  import type { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FILE_SERVER } from '@/config/setting';
  import { useUserStore } from '@/store/modules/user';

  const userStore = useUserStore();
  // 当前用户信息
  const loginUser = computed(() => userStore.info ?? {});
  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Customer | null;
  }>();

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

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);

  // 用户信息
  const form = reactive<Customer>({
    customerId: undefined,
    creditCode: '',
    name: '',
    fullName: '',
    avatar: '',
    phone: '',
    telPhone: '',
    contact: '',
    address: '',
    remark: '',
    sortNumber: 100,
    createTime: undefined,
    userId: 0,
  });

  // 已上传数据, 可赋初始值用于回显
  const images = ref(<any>[]);

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

  // 表单验证规则
  const rules = reactive({
    name: [
      {
        required: true,
        type: 'string',
        message: '请输入客户名称',
        trigger: 'blur'
      }
    ],
    creditCode: [
      {
        required: true,
        type: 'string',
        message: '请输入客户标识',
        trigger: 'blur'
      }
    ]
  });

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

  /* 保存编辑 */
  const save = () => {
    validate()
      .then(() => {
        loading.value = true;
        // 去除空格
        form.name = form.name?.replace(/\s*/g, '');
        // 判断权限
        // if (loginUser.value.roles?.[0].roleCode != 'admin'){
        //   form.status = '1';
        // }
        const data = {
          ...form
        };
        // 转字符串
        const saveOrUpdate = isUpdate.value ? updateCustomer : addCustomer;
        saveOrUpdate(data)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  // 上传文件
  const onUpload = (d: ItemType) => {
    uploadFile(<File>d.file)
      .then((result) => {
        form.avatar = result.path;
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          loading.value = false;
          // 头像赋值
          images.value = [];
          if(props.data.avatar){
            images.value.push({ uid:1, url: FILE_SERVER + props.data.avatar, status: '' });
          }
          assignObject(form, props.data);
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
<style lang="less"></style>
