<template>
  <Modal :maskClosable="false" :keyboard="false" v-model:open="data.isShowModal" :footer="null"
    :title="$t('robot.account.editTitle')" width="50%" @cancel="_close">
    <Form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" labelAlign="left" :labelWrap="true">
      <Row :gutter="24">
        <!-- <Col :span="12">
          <FormItem :label="$t('robot.account.code')" name="code">
            <Input v-model:value="form.code" allowClear disabled :placeholder="$t('common.placeholderIn')"/>
          </FormItem>
        </Col> -->
        <Col :span="12">
          <FormItem :label="$t('robot.account.email')" name="email">
            <Input v-model:value="form.email" allowClear disabled :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.password')" name="password">
            <Input v-model:value="form.password" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.status')" name="status">
            <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="form.status" allowClear
              :placeholder="$t('common.placeholderIn')">
              <SelectOption v-for="(item, index) in data.statusOptions" :key="index" :value="item.value"
                :label="item.label" :text="item.label">{{ item.label }}
              </SelectOption>
            </Select>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.groupId')" name="groupId">
            <Select allow-clear showSearch :filterOption="selectFilterOption" v-model:value="form.groupId" allowClear
              :placeholder="$t('common.placeholderIn')" @change="handleGroupChange">
              <SelectOption v-for="(item, index) in data.groupOptions" :key="index" :value="item.uuid"
                :label="item.groupName" :text="item.groupName">{{ item.groupName }}
              </SelectOption>
            </Select>
          </FormItem>
        </Col>
        <!-- <Col :span="12">
          <FormItem :label="$t('robot.account.groupName')" name="groupName">
            <Input v-model:value="form.groupName" allowClear :placeholder="$t('common.placeholderIn')" disabled/>
          </FormItem>
        </Col> -->
        <!-- <Col :span="12">
          <FormItem :label="$t('robot.account.managerId')" name="managerId">
            <Input v-model:value="form.managerId" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.managerName')" name="managerName">
            <Input v-model:value="form.managerName" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col> -->
        <Col :span="12">
          <FormItem :label="$t('robot.account.userNumber')" name="userNumber">
            <Input v-model:value="form.userNumber" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.countryMobileCode')" name="countryMobileCode">
            <Input v-model:value="form.countryMobileCode" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.mobile')" name="mobile">
            <Input v-model:value="form.mobile" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.nickname')" name="nickname">
            <Input v-model:value="form.nickname" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.headerIconUrl')" name="headerIconUrl">
            <div style="display: flex; align-items: center; gap: 10px;">
              <img v-if="form.headerIconUrl" :src="form.headerIconUrl" alt="头像预览" style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px; border: 1px solid #d9d9d9;" />
              <Upload
                :showUploadList="false"
                accept="image/*"
                :beforeUpload="handleUpload"
              >
                <Button :loading="data.uploadLoading">
                  <upload-outlined></upload-outlined>
                  {{ form.headerIconUrl ? '更换头像' : '上传头像' }}
                </Button>
              </Upload>
              <Button v-if="form.headerIconUrl" danger size="small" @click="handleRemoveAvatar">删除</Button>
            </div>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem :label="$t('robot.account.userId')" name="userId">
            <Input v-model:value="form.userId" allowClear :placeholder="$t('common.placeholderIn')" />
          </FormItem>
        </Col>
        <Col :span="24">
          <FormItem :label-col="{ span: 3 }" :label="$t('robot.account.notes')" name="notes">
            <TextArea v-model:value="form.notes" allowClear :placeholder="$t('common.placeholderIn')" :rows="3" />
          </FormItem>
        </Col>
      </Row>
      <FormItem style="text-align: right">
        <Button @click="_close" :disabled="data.loading">{{ $t('common.cancel') }}</Button>
        <Button danger style="margin-left: 10px" @click="handleResetForm" :disabled="data.loading">
          {{ $t('common.reset') }}
        </Button>
        <Button type="primary" style="margin-left: 10px" @click="handleSubmit" :loading="data.loading"
          :disabled="data.loading">{{ $t('common.confirm') }}
        </Button>
      </FormItem>
    </Form>
  </Modal>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { $t } from '@vben/locales';
import { Modal, Form, Input, Select, Row, Col, Button, message, Upload } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { robotAccount, robotGroup, base } from '#/api';

const FormItem = Form.Item;
const SelectOption = Select.Option;
const TextArea = Input.TextArea;

interface Emits {
  (e: 'close', submit: Boolean): void
}

const emits = defineEmits<Emits>()

const data = reactive({
  isShowModal: false,
  loading: false,
  uploadLoading: false,
  statusOptions: [
    { label: $t('robot.account.statusOptions.v0'), value: 0 },
    { label: $t('robot.account.statusOptions.v1'), value: 1 }
  ],
  groupOptions: [],
  groupLoading: false
})

const form = reactive({
  uuid: null,
  code: '',
  email: '',
  password: '',
  notes: '',
  status: undefined,
  groupId: undefined,
  groupName: '',
  managerId: undefined,
  managerName: '',
  userNumber: '',
  countryMobileCode: '',
  mobile: '',
  nickname: '',
  headerIconUrl: '',
  userId: undefined
})

// 选择框过滤方法
const selectFilterOption = (input: string, option: any) => {
  return option.text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
}

// 加载分组数据
const loadGroupOptions = async () => {
  data.groupLoading = true;
  try {
    const res = await robotGroup.queryList({});
    if (!res.error && res.data) {
      data.groupOptions = res.data;
    }
  } catch (error) {
    console.error('加载分组数据失败:', error);
  } finally {
    data.groupLoading = false;
  }
}

// 分组选择变化处理
const handleGroupChange = (value: string) => {
  if (value) {
    const selectedGroup = data.groupOptions.find(group => group.uuid === value);
    if (selectedGroup) {
      form.groupName = selectedGroup.groupName;
    }
  } else {
    form.groupName = '';
  }
}

// 表单规则
const rules = reactive({
  // 编辑时部分字段不可编辑，不需要验证
})

const formRef = ref();

function handleSubmit() {
  data.loading = true;
  formRef.value.validate().then(() => {
    robotAccount.updateByUid(form).then((res) => {
      if (res.error) {
        return;
      }
      message?.success($t('common.editSuccess'));
      _close(true);
    })
  }).finally(() => {
    data.loading = false;
  })
}

function handleResetForm() {
  formRef.value.resetFields();
}

function _close(submit = false) {
  data.isShowModal = false;
  formRef.value.resetFields();
  emits('close', submit);
}

function _open(item) {
  data.isShowModal = true;
  Object.assign(form, item);
  loadGroupOptions();
}

defineExpose({
  _open
})

// 上传前验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件！');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！');
    return false;
  }
  return false; // 阻止默认上传，使用自定义上传
}

// 自定义上传处理
const handleUpload =async (file, fileList) => {
  data.uploadLoading = true;
  try {
    // 调用上传接口
    const formData = new FormData();
    formData.append('file', file);

    const res = await base.uploadImage(formData);

    if (res.code === '00000' && res.data) {
      form.headerIconUrl = res.data.url
    } else {
      message.error('图片上传失败');
    }
  } catch (error) {
    message.error('图片上传异常');
    console.error('图片上传失败:', error);
  } finally {
    data.uploadLoading = false;
  }
  return false;
};

// 删除头像
const handleRemoveAvatar = () => {
  form.headerIconUrl = '';
}
</script>