<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="principal">
          <el-input v-model="ruleForm.principal" />
        </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.principal" @click="resetDraw">重置</el-button>
        <el-button v-if="!props.detail.principal" type="primary" @click="addNewType(ruleFormRef)">
          提交
        </el-button>
        <el-button v-if="props.detail.principal" 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 { addWorkspace, editWorkspace } from '@/api/scene/sceneOperate';

  const props = defineProps<{
    allCodes: string[];
    detail: {
      id?: number;
      name?: string;
      code?: string;
      seniorScene?: string;
      principal?: string;
      addEnable?: ENABLED;
    };
  }>();

  const emit = defineEmits<{
    (e: 'onOk'): unknown;
    (e: 'onClose'): unknown;
  }>();

  const title = computed(() => {
    if (props.detail.principal) {
      return '编辑工位';
    }
    return '添加工位';
  });

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

  interface RuleForm {
    name: string; //名称
    seniorScene: string; //上级场景
    code: string; //代码
    principal?: string; //负责人
    addEnable?: ENABLED;
  }
  const ruleForm = reactive<RuleForm>({
    name: '',
    seniorScene: '',
    code: '',
    principal: '',
    addEnable: ENABLED.TRUE,
  });
  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' },
    ],
    principal: [
      { required: true, message: '负责人不能为空', trigger: 'blur' },
      { min: 1, max: 100, message: 'Length should be 1 to 100', trigger: 'blur' },
    ],
  });

  watch(
    () => props.detail,
    (data) => {
      ruleForm.name = data.name!;
      ruleForm.seniorScene = data.seniorScene!;
      ruleForm.code = data.code!;
      ruleForm.principal = data.principal;
      ruleForm.addEnable = data.addEnable;
    },
    { immediate: true },
  );

  //添加新公司的提交
  const addNewType = (formEl: FormInstance | undefined) => {
    if (!formEl) return;

    formEl.validate((valid) => {
      if (!valid) {
        return;
      }
      if (props.allCodes.indexOf(ruleForm.code) > -1) {
        ElMessageBox.confirm('场景代码重复，请重新填写', '代码重复', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'error',
        })
          .then(() => {
            console.log('场景代码重复，请重新填写');
          })
          .catch(() => {
            console.log('取消删除物件');
          });
      } else {
        const newAddData = {
          code: ruleForm.code,
          workshopId: props.detail.id,
          isDeleted: 0,
          name: ruleForm.name,
          principal: ruleForm.principal,
          status: Number(ruleForm.addEnable),
          serial: 0,
        };
        addWorkspace(newAddData)
          .catch((err) => {
            console.log(err);
          })
          .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.indexOf(ruleForm.code) > -1) {
        if (props.detail.code !== ruleForm.code) {
          ElMessageBox.confirm('场景代码重复，请重新填写', '代码重复', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'error',
          })
            .then(() => {
              console.log('代码重复');
            })
            .catch(() => {
              console.log('取消删除物件');
            });
          return;
        }
      }

      const editNewWorkspaceData = {
        code: ruleForm.code,
        name: ruleForm.name,
        status: Number(ruleForm.addEnable),
        id: props.detail.id,
        principal: ruleForm.principal,
      };

      //编辑车间并上传
      editWorkspace(editNewWorkspaceData)
        .catch((err) => {
          console.log(err);
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          emit('onOk');
        });
    });
  };

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

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