<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="750"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改部位' : '新建部位'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 6, sm: 6, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 18, sm: 20, xs: 24 } : { flex: '1' }
      "
    >
      <a-row :gutter="16">
        <a-col
          v-bind="styleResponsive ? { md: 22, sm: 24, xs: 24 } : { span: 12 }"
        >
          <a-form-item label="设备类型" name="equipmentType">
            <TowerEquipmentType
              v-model:value="form.equipmentType"
              valueField="label"
              placeholder="请选择设备类型"
              class="ele-fluid"
            />
          </a-form-item>
          <a-form-item label="部位名称" name="name">
            <a-input
              allow-clear
              placeholder="请输入部位名称"
              v-model:value="form.name"
            />
          </a-form-item>
          <a-form-item label="推送系统目标" name="pushSystem">
            <DictSelect
              dict-code="PushSystem"
              placeholder="推送系统目标"
              v-model:value="form.pushSystem"
            />
          </a-form-item>
          <a-form-item label="其他项目对应的值" name="otherParam">
            <a-textarea
              :rows="3"
              :maxlength="200"
              placeholder="其他项目对应的值"
              v-model:value="form.otherParam"
            />
          </a-form-item>
          <a-form-item label="部位类型" name="type">
            <a-checkbox-group
              v-model:value="placeType"
              :options="typeOptions"
              @change="onChangeType"
            />
          </a-form-item>
          <a-form-item label="默认是否显示" name="isShow">
            <a-switch
              checked-children="是"
              un-checked-children="否"
              :checked="form.isShow"
              @update:checked="updateHideValue"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <StandardList :place-id="form.placeId" v-model:value="form.standard" />
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import StandardList from './standard-list.vue';
  import type { TowerPlace } from '@/api/tower/param/place/model';
  import { addTowerPlace, updateTowerPlace } from '@/api/tower/param/place';
  import DictSelect from '@/views/search/components/apps/components/dict-select.vue';
  import { createCode } from '@/utils/common';
  import { listTowerPlaceStandard } from '@/api/tower/param/standard';

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

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

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: TowerPlace | null;
  }>();

  const formRef = ref<FormInstance | null>(null);
  // 是否是修改
  const isUpdate = ref(false);
  // 提交状态
  const loading = ref(false);
  const typeOptions = ['巡检部位', '保养部位'];
  const placeType = ref<string[]>([]);

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<TowerPlace>({
    name: '',
    placeCode: `BW${createCode()}`,
    placeId: undefined,
    equipmentType: undefined,
    standard: [],
    type: undefined,
    isShow: true,
    status: 0,
    sortNumber: 100
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    equipmentType: [
      {
        required: true,
        message: '请选择设备类型',
        type: 'string',
        trigger: 'blur'
      }
    ],
    name: [
      {
        required: true,
        message: '请输入设备名称',
        type: 'string',
        trigger: 'blur'
      }
    ],
    model: [
      {
        required: true,
        message: '请输入部位',
        type: 'string',
        trigger: 'blur'
      }
    ],
    type: [
      {
        required: true,
        message: '请选择部位类型',
        type: 'string',
        trigger: 'blur'
      }
    ],
    sortNumber: [
      {
        required: true,
        message: '请输入排序号',
        type: 'number',
        trigger: 'blur'
      }
    ]
  });

  const updateHideValue = (isShow) => {
    if (isShow) {
      form.isShow = true;
    }
    if (!isShow) {
      form.isShow = false;
    }
  };

  const onChangeType = (e) => {
    if (e[0] == '巡检部位') {
      form.type = '巡检';
    }
    if (e[0] == '保养部位') {
      form.type = '保养';
    }
    if (placeType.value.length == 2) {
      form.type = '巡检和保养';
    }
    console.log(form.type);
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        console.log(form.type);
        const categoryForm = {
          ...form,
          isShow: form.isShow ? 1 : 0
        };
        const saveOrUpdate = isUpdate.value ? updateTowerPlace : addTowerPlace;
        saveOrUpdate(categoryForm)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

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

  const reload = () => {
    // 加载检查标准
    listTowerPlaceStandard({ placeId: form.placeId }).then((list) => {
      form.standard = list;
    });
  };

  reload();

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields({
            ...props.data
          });
          // 是否默认显示
          form.isShow = false;
          if (Number(props.data.isShow) == 1) {
            form.isShow = true;
          }
          placeType.value = [];
          if (props.data.type == '巡检和保养') {
            placeType.value[0] = '巡检部位';
            placeType.value[1] = '保养部位';
          }
          if (props.data.type == '巡检') {
            placeType.value[0] = '巡检部位';
          }
          if (props.data.type == '保养') {
            placeType.value[0] = '保养部位';
          }
          reload();
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>

<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
</style>
