<template>
  <FullPage style="min-height: calc(100vh - 216px)">
    <div>
      <Form layout="vertical" :rules="rule" :model="form" ref="formRef">
        <Row :gutter="24">
          <Col :span="12">
            <FormItem label="名称" name="name"> <Input placeholder="请输入名称" v-model:value="form.name" /> </FormItem
          ></Col>
          <Col :span="12">
            <FormItem name="targetType">
              <template #label>
                <Space>
                  类型
                  <Tooltip>
                    <template #title>
                      <div>产品：以产品维度告警，某产品下的多个设备异常仅发送一条告警。</div>
                      <div>设备：以设备维度告警，任何设备异常即发送一条告警。</div>
                      <div>组织：以组织维度告警，某组织下的多个设备异常仅发送一条告警。</div>
                      <div>其他：以场景联动维度告警，某场景下的多个设备异常仅发送一条告警。</div>
                    </template>
                    <AIcon type="QuestionCircleOutlined" style="color: rgb(136, 136, 136); font-size: 12px" />
                  </Tooltip>
                </Space>
              </template>
              <Select :options="options" v-model:value="form.targetType" :disabled="selectDisable" />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="级别" name="level">
          <RadioGroup v-model:value="form.level" class="levelSelect">
            <RadioButton v-for="(item, index) in levelOption" :key="index" :value="item.value">
              <div style="text-align: center; margin-top: 10px; font-size: 15px; width: 90%">
                <img :src="getImage(`/alarm/alarm${index + 1}.png`)" style="height: 40px" alt="" />{{ item.label }}
              </div>
            </RadioButton>
          </RadioGroup>
        </FormItem>
        <FormItem label="说明" name="description">
          <Textarea v-model:value="form.description" showCount :maxlength="200" />
        </FormItem>
        <Space>
          <JButton @click="close">取消</JButton>
          <PermissionButton type="primary" :loading="loading" @click="handleSave">保存</PermissionButton>
        </Space>
      </Form>
    </div>
  </FullPage>
</template>

<script lang="ts" setup>
  import { getTargetTypes, save, detail, updata } from '../../../../../../api/rule-engine/configuration';
  import { queryLevel } from '../../../../../../api/rule-engine/config';
  import { _query } from '../../../../../../api/rule-engine/scene';
  import { getImage, onlyMessage } from '@jdlinker/utils';
  import { useAlarmConfigurationStore } from '@jdlinker/func';
  import { storeToRefs } from 'pinia';
  import { ref, watch } from 'vue';
  import { PermissionButton, FullPage } from '@jdlinker/ui';
  // @ts-ignore
  import { Button as JButton, Form, Row, Col, FormItem, Space, Tooltip, AIcon, Select, RadioGroup, RadioButton, Textarea, Input } from 'linker-ui-components';

  const emit = defineEmits(['update:value', 'close', 'change']);
  const props = defineProps({
    id: {
      type: String,
      defult: ''
    }
  });
  // const route = useRoute();
  let selectDisable = ref(false);
  const alarmConfigurationStore = useAlarmConfigurationStore();
  let { configurationData } = storeToRefs(alarmConfigurationStore);

  const queryData = () => {
    if (props.id) {
      detail(props.id).then((res) => {
        if (res.code === 200) {
          form.value = res?.result;
          configurationData.value.current = res.result;
          _query({ terms: [props?.id] }).then((resq) => {
            if (resq.code === 200) {
              selectDisable.value = !!resq.result.data?.length;
            }
          });
        }
      });
    }
  };
  const rule = {
    name: [
      {
        required: true,
        message: '请输入名称'
      },
      {
        max: 64,
        message: '最多输入64个字符'
      }
    ],
    targetType: [
      {
        required: true,
        message: '请选择类型'
      }
    ],
    level: [
      {
        required: true,
        message: '请选择级别'
      }
    ],
    description: [
      {
        max: 200,
        message: '最多可输入200个字符'
      }
    ]
  };
  const form = ref({
    level: '',
    targetType: '',
    name: '',
    description: '',
    stateValue: ''
  });
  let options = ref();
  let levelOption = ref();
  let loading = ref(false);
  const formRef = ref();
  // const menuStory = useMenuStore();
  const getSupports = async () => {
    let res = await getTargetTypes();
    if (res.code === 200) {
      options.value = res.result.map((item: { id: string; name: string }) => ({
        label: item.name,
        value: item.id
      }));
    }
  };
  getSupports();
  const getLevel = () => {
    queryLevel().then((res) => {
      if (res.code === 200) {
        levelOption.value = res.result?.levels
          ?.filter((i: any) => i?.level && i?.title)
          .map((item: { level: number; title: string }) => ({
            label: item.title,
            value: item.level
          }));
      }
    });
  };
  getLevel();
  const handleSave = async () => {
    loading.value = true;
    formRef.value
      ?.validate()
      .then(async () => {
        const res = props.id ? await updata(form.value) : await save(form.value);
        if (res.code === 200) {
          onlyMessage('操作成功,请配置关联的场景联动', 'success');
          loading.value = false;
          emit('change', form.value.targetType);
          if (res.result?.id) {
            emit('update:value', res.result?.id);
            // menuStory.jumpPage(
            //     'rule-engine/Alarm/Configuration/Save',
            //     {},
            //     { id: res.result?.id },
            // );
          }
          if (!props.id) {
            configurationData.value.current = res.result;
          }
        }
      })
      .catch((error) => {
        loading.value = false;
        console.log(error);
      });
  };
  queryData();
  watch(
    () => props.id,
    () => {
      queryData();
    }
  );

  const close = () => {
    emit('close');
  };
</script>
<style lang="less" scoped>
  .ant-radio-button-wrapper {
    margin: 10px 15px 0 0;
    width: 20%;
    height: 100%;
  }
  .levelSelect {
    display: flex;
    width: 100%;
  }
  img {
    display: inline-block;
  }
</style>
