<template>
  <div>
    <el-drawer
      class="test"
      :model-value="true"
      @close="() => emit('onClose')"
      with-header="true"
      size="35%"
    >
      <template #header="{ titleId }">
        <p :id="titleId">{{ title }}</p>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        size="default"
        status-icon
      >
        <el-form-item label="车间名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="上级场景" prop="seniorScene">
          <el-input v-model="ruleForm.seniorScene" disabled />
        </el-form-item>
        <el-form-item label="车间代码" prop="code">
          <el-input v-model="ruleForm.code" />
        </el-form-item>
        <el-form-item label="场景标签" prop="tagWorkshop">
          <el-radio-group
            v-model="ruleForm.tagWorkshop"
            size="10px"
            style="display: flex; justify-content: space-between"
          >
            <el-radio-button
              v-for="item in props.detail.tagList"
              :key="item.id"
              :label="item.id!"
              class="tag-select"
              style="margin-right: 10px"
              >{{ item.name }}</el-radio-button
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="车间模板" prop="templateWorkshop">
          <el-radio-group
            v-model="ruleForm.templateWorkshop"
            size="10px"
            style="display: flex; justify-content: space-between"
          >
            <el-radio-button
              v-for="item in props.workshopTemplateList"
              :key="item.id"
              :label="item.id!"
              class="tag-select"
              >{{ item.name }}</el-radio-button
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="ruleForm.addEnable"
            :active-value="ENABLED.TRUE"
            :inactive-value="ENABLED.FALSE"
            class="switchUse"
          />
        </el-form-item>
      </el-form>
      <div style="position: absolute; left: 108px; bottom: 67px">
        <el-button v-if="!props.detail.companyId" @click="resetDraw">重置</el-button>
        <el-button v-if="!props.detail.companyId" type="primary" @click="addNewType(ruleFormRef)">
          提交
        </el-button>
        <el-button v-if="props.detail.companyId" type="primary" @click="editedSub(ruleFormRef)">
          提交
        </el-button>
      </div>
    </el-drawer></div
  >
</template>

<script setup lang="ts">
  import { computed, reactive, ref, defineProps, defineEmits, watch } from 'vue';
  import { ENABLED } from './constant';
  import { ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
  import { LabelModuleListType, addWorkshop, editWorkshop } from '@/api/scene/sceneOperate';
  import {
    WorkshopModuleType,
    addWorkshopModuleLabel,
    editWorkshopModuleLabel,
  } from '@/api/scene/secene-templet';

  const props = defineProps<{
    allCodes: string[];
    workshopTemplateList: WorkshopModuleType[];
    detail: {
      id?: number;
      name?: string;
      code?: string;
      seniorScene?: string;
      tagWorkshop?: number;
      templateWorkshop?: number;
      addEnable?: ENABLED;
      tagList?: LabelModuleListType[];
      companyId?: number;
    };
  }>();

  //将表单数据传至父组件
  const emit = defineEmits<{
    (e: 'onOk'): unknown;
    (e: 'onClose'): unknown;
  }>();

  //表格中的规则
  const ruleFormRef = ref<FormInstance>();

  const title = computed(() => {
    if (props.detail.companyId) {
      return '编辑车间';
    }
    return '添加车间';
  });

  interface RuleForm {
    name: string; //名称
    seniorScene: string; //上级场景
    code: string; //代码
    tagWorkshop?: number | null; //场景标签  车间
    templateWorkshop?: number | null; //车间模板
    addEnable?: ENABLED; //状态
  }
  const ruleForm = reactive<RuleForm>({
    name: '',
    seniorScene: '',
    code: '',
    tagWorkshop: null,
    templateWorkshop: null,
    addEnable: ENABLED.TRUE,
    // principal: '',
  });
  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '车间名称不能为空', trigger: 'blur' },
      { min: 1, max: 100, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    seniorScene: [
      { required: true, message: '', trigger: 'blur' },
      { min: 1, max: 100, message: 'Length should be 1 to 100', trigger: 'blur' },
    ],
    code: [
      { required: true, message: '车间代码不能为空', trigger: 'blur' },
      { min: 1, max: 100, message: 'Length should be 1 to 100', trigger: 'blur' },
    ],
    tagWorkshop: [{ required: true, message: '请选择场景标签', trigger: 'blur' }],
    templateWorkshop: [{ required: true, message: '请选择车间模板', trigger: 'blur' }],
  });

  //编辑时需要传入子组件的数据
  watch(
    () => props.detail,
    (data) => {
      ruleForm.name = data.name!;
      ruleForm.seniorScene = data.seniorScene!;
      ruleForm.code = data.code!;
      ruleForm.tagWorkshop = data.tagWorkshop;
      ruleForm.templateWorkshop = data.templateWorkshop;
      ruleForm.addEnable = data.addEnable;
    },
    { immediate: true },
  );

  //添加新车间的提交
  const addNewType = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid) => {
      if (!valid) {
        return;
      }
      const newAddData = {
        code: ruleForm.code,
        companyId: props.detail.id,
        sceneLabelId: ruleForm.tagWorkshop!,
        isDeleted: 0,
        name: ruleForm.name,
        status: Number(ruleForm.addEnable),
        serial: 0,
      };

      if (props.allCodes.includes(ruleForm.code)) {
        ElMessageBox.confirm('场景代码重复，请重新填写', '代码重复', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'error',
        })
          .then(() => {
            console.log('场景代码重复，请重新填写');
          })
          .catch(() => {
            console.log('取消删除物件');
          });
      } else {
        addWorkshop(newAddData)
          .then((res) => {
            const newWorkshopModule = {
              workshopId: res,
              isDeleted: 0,
              workshopModuleId: ruleForm.templateWorkshop!,
            };
            return addWorkshopModuleLabel(newWorkshopModule);
          })
          .catch((err) => {
            console.log(err);
          })
          .finally(() => {
            emit('onOk');
          });
      }
    });
  };

  //编辑公司时的提交
  const editedSub = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid) => {
      if (!valid) {
        return;
      }
      if (props.allCodes.includes(ruleForm.code)) {
        if (props.detail.code !== ruleForm.code) {
          ElMessageBox.confirm('场景代码重复，请重新填写', '代码重复', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'error',
          })
            .then(() => {
              console.log('代码重复');
            })
            .catch(() => {
              console.log('取消删除物件');
            });
          return;
        }
      }

      const editNewWorkshopData = {
        code: ruleForm.code,
        sceneLabelId: ruleForm.tagWorkshop!,
        name: ruleForm.name,
        status: Number(ruleForm.addEnable),
        id: props.detail.id,
      };

      editWorkshop(editNewWorkshopData)
        .then(() => {
          const editWorkshopModule = {
            isDeleted: 0,
            workshopId: props.detail.id,
            workshopModuleId: ruleForm.templateWorkshop!,
          };
          return editWorkshopModuleLabel(editWorkshopModule);
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          emit('onOk');
        });
    });
  };

  //重置编辑框
  const resetDraw = () => {
    ruleForm.name = '';
    ruleForm.code = '';
    ruleForm.addEnable = ENABLED.TRUE;
    ruleForm.templateWorkshop = null;
    ruleForm.tagWorkshop = null;
  };
</script>

<style scoped>
  .tag-select {
    margin-right: 10px;
    margin-bottom: 10px;
    border-radius: 4px;
    border: 1px solid rgba(0, 0, 0, 0.15);
  }
</style>
