<template>
  <Modal
    :centered="true"
    :maskClosable="false"
    width="650px"
    :open="true"
    :title="!!data?.id ? '编辑' : '新增'"
    @ok="handleSave"
    @cancel="handleCancel"
    :confirmLoading="loading"
  >
    <div style="margin-top: 20px; padding: 0 20px">
      <Form :layout="'vertical'" ref="formRef" :model="modelRef">
        <Row type="flex">
          <Col flex="180px">
            <FormItem name="photoUrl">
              <JProUpload accept="image/jpeg,image/png" v-model="modelRef.photoUrl" />
            </FormItem>
          </Col>
          <Col flex="auto">
            <FormItem
              name="id"
              :rules="[
                {
                  pattern: /^[a-zA-Z0-9_\-]+$/,
                  message: '请输入英文或者数字或者-或者_'
                },
                {
                  max: 64,
                  message: '最多输入64个字符'
                },
                {
                  validator: vailId,
                  trigger: 'blur'
                }
              ]"
            >
              <template #label>
                <span>
                  ID
                  <Tooltip title="若不填写，系统将自动生成唯一ID">
                    <JAIcon type="QuestionCircleOutlined" style="margin-left: 2px" />
                  </Tooltip>
                </span>
              </template>
              <Input v-model:value="modelRef.id" placeholder="请输入ID" :disabled="!!data?.id" />
            </FormItem>
            <FormItem
              label="名称"
              name="name"
              :rules="[
                {
                  required: true,
                  message: '请输入名称'
                },
                {
                  max: 64,
                  message: '最多输入64个字符'
                }
              ]"
            >
              <Input v-model:value="modelRef.name" placeholder="请输入名称" />
            </FormItem>
          </Col>
        </Row>
        <FormItem
          name="productId"
          :rules="[
            {
              required: true,
              message: '请选择所属产品'
            }
          ]"
        >
          <template #label>
            <span
              >所属产品
              <Tooltip title="只能选择“正常”状态的产品">
                <JAIcon type="QuestionCircleOutlined" style="margin-left: 2px" />
              </Tooltip>
            </span>
          </template>
          <Select
            showSearch
            v-model:value="modelRef.productId"
            :disabled="!!data?.id"
            placeholder="请选择状态为“正常”的产品"
          >
            <SelectOption :value="item.id" v-for="item in productList" :key="item.id" :label="item.name">{{
              item.name
            }}</SelectOption>
          </Select>
        </FormItem>
        <FormItem
          label="说明"
          name="describe"
          :rules="[
            {
              max: 200,
              message: '最多输入200个字符'
            }
          ]"
        >
          <Textarea v-model:value="modelRef.describe" placeholder="请输入说明" showCount :maxlength="200" />
        </FormItem>
      </Form>
    </div>
  </Modal>
</template>

<script lang="ts" setup>
  import { queryNoPagingPost } from '../../../../api/device/product';
  import { isExists, update } from '../../../../api/device/instance';
  import { getImage, onlyMessage } from '@jdlinker/utils';
  import { ref, watch, reactive } from 'vue';
  // @ts-ignore
  import {
    AIcon as JAIcon,
    Modal,
    Tooltip,
    Select,
    SelectOption,
    Form,
    Row,
    Col,
    FormItem,
    Textarea,
    Input
  } from 'linker-ui-components';
  import { JProUpload } from '@jdlinker/ui';

  const emit = defineEmits(['close', 'save']);
  const props = defineProps({
    data: {
      type: Object,
      default: undefined
    }
  });
  const productList = ref<Record<string, any>[]>([]);
  const loading = ref<boolean>(false);

  const formRef = ref();

  const modelRef = reactive({
    productId: undefined,
    id: undefined,
    name: '',
    describe: '',
    photoUrl: getImage('/device/instance/device-card.png')
  });

  const vailId = async (_: Record<string, any>, value: string) => {
    // @ts-ignore
    if (!props?.data?.id && value) {
      const resp = await isExists(value);
      if (resp.code === 200 && resp.result) {
        return Promise.reject('ID重复');
      } else {
        return Promise.resolve();
      }
    } else {
      return Promise.resolve();
    }
  };

  watch(
    () => props.data,
    (newValue: any) => {
      queryNoPagingPost({
        paging: false,
        sorts: [{ name: 'createTime', order: 'desc' }],
        terms: [
          {
            terms: [
              {
                termType: 'eq',
                column: 'state',
                value: 1
              }
            ]
          }
        ]
      }).then((resp) => {
        if (resp.code === 200) {
          productList.value = resp.result as Record<string, any>[];
        }
      });
      Object.assign(modelRef, newValue);
      // description 和 describe 处理
      modelRef.describe = newValue?.describe || newValue?.description;
    },
    { immediate: true, deep: true }
  );

  const handleCancel = () => {
    emit('close');
    formRef.value.resetFields();
  };

  const handleSave = () => {
    formRef.value
      .validate()
      .then(async (_data: any) => {
        loading.value = true;
        const obj = { ..._data };
        if (!obj.id) {
          delete obj.id;
        }
        // @ts-ignore
        const resp = await update(obj).finally(() => {
          loading.value = false;
        });
        if (resp) {
          onlyMessage('操作成功！', 'success');
          emit('save');
          formRef.value.resetFields();
        }
      })
      .catch((err: any) => {
        console.log('error', err);
      });
  };
</script>
<style scoped lang="less">
  .ant-col {
    width: 0;
  }
  .ant-form-item {
    margin-bottom: 12px;
  }
</style>
