<template>
  <div>
    <el-drawer
      ref="companyDrawerRef"
      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="90px"
        class="demo-ruleForm"
        size="default"
        status-icon
      >
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="ruleForm.name" style="width: 200px" />
        </el-form-item>
        <el-form-item label="上级场景" prop="seniorScene">
          <el-input v-model="ruleForm.seniorScene" style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="公司代码" prop="code">
          <el-input v-model="ruleForm.code" style="width: 200px" />
        </el-form-item>
        <el-form-item label="标签&模板" required>
          <div style="display: flex; flex-direction: column; align-items: flex-start">
            <div
              v-for="(item, index) in ruleForm.selectItems"
              :key="index"
              style="margin-bottom: 16px; display: flex"
            >
              <el-select v-model="item.tag" placeholder="请选择标签" style="width: 126px">
                <el-option
                  v-for="item1 in props.sceneList"
                  :key="item1.id"
                  :label="item1.name"
                  :value="item1.id"
                />
              </el-select>
              <img
                src="@/assets/icons/link.png"
                alt=""
                style="width: 16px; margin-left: 2px; margin-right: 2px" />
              <el-select v-model="item.template" placeholder="请选择模板" style="width: 126px">
                <el-option
                  v-for="item2 in props.templateList"
                  :key="item2.id"
                  :label="item2.name"
                  :value="item2.id"
                />
              </el-select>
              <img
                src="@/assets/icons/close.png"
                @click="deleScene(index)"
                alt=""
                style="
                  width: 13px;
                  height: 13px;
                  margin-top: 10px;
                  margin-left: 3px;
                  cursor: pointer;
                "
            /></div>
            <div style="width: 200px">
              <el-icon size="28px" @click="addChange" style="cursor: pointer"
                ><CirclePlus /></el-icon
            ></div>
          </div>
        </el-form-item>
        <el-form-item label="所在省市" prop="regionCode">
          <el-select v-model="ruleForm.regionCode" placeholder="请选择省市" style="width: 200px">
            <el-option
              v-for="item in provinceList"
              :key="item.regionCode"
              :label="item.regionName"
              :value="item.regionCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="坐标经度" prop="longitude"
          ><el-input v-model="ruleForm.longitude" type="number" style="width: 200px"></el-input
        ></el-form-item>
        <el-form-item label="坐标纬度" prop="latitude"
          ><el-input v-model="ruleForm.latitude" type="number" style="width: 200px"></el-input
        ></el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" style="width: 200px" />
        </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.comEdit" @click="resetDrawCom">重置</el-button>
        <el-button type="primary" v-if="!props.comEdit" @click="newCompanyAdd"> 提交 </el-button>
        <el-button type="primary" v-if="props.comEdit" @click="editedSub(ruleFormRef)">
          提交
        </el-button>
      </div>
    </el-drawer></div
  >
</template>

<script setup lang="ts">
  import { computed, reactive, ref, defineProps, defineEmits, watch, onMounted } from 'vue';
  import {
    addCompanyModuleLabel,
    editCompanyModuleLabel,
    SceneLabelType,
    TemplateType,
  } from '@/api/scene/secene-templet';
  import { ENABLED } from './constant';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { CirclePlus } from '@element-plus/icons-vue';
  import { addCompany, editCompany } from '@/api/scene/sceneOperate';
  import { getProvinceList } from '@/api/system/region';
  import { useRequest } from 'vue-hooks-plus';
  import { string } from 'vue-types';

  interface SelectItemType {
    tag: string;
    template: string;
  }

  const props = defineProps<{
    sceneList: SceneLabelType[];
    templateList: TemplateType[];
    allCodes: string[];
    comEdit: boolean;
    detail: {
      id?: number;
      name?: string;
      code?: string;
      seniorScene?: string;
      addEnable?: ENABLED;
      selectItems?: SelectItemType[];
      remark?: string;
      longitude?: number; //经度
      latitude?: number; //纬度
      regionCode: string;
    };
  }>();

  const title = computed(() => {
    if (props.comEdit) {
      return '编辑公司';
    }
    return '添加公司';
  });
  const emit = defineEmits<{
    (e: 'onOk'): unknown;
    (e: 'onClose'): unknown;
  }>();

  //表格中的规则
  const ruleFormRef = ref<FormInstance>();
  //匹配规则
  // const pattern = /经度\s*[:：]\s*([0-9.]+)\s*[;；]\s*纬度\s*[:：]\s*([0-9.]+)/;

  interface RuleForm {
    name: string; //名称
    seniorScene: string; //上级场景
    code: string; //代码
    sceneCode: string; //场景代码
    tagCom?: string[]; //公司场景标签 可选多个
    templateCom?: string[]; //公司场景模板 可选多个
    tagWorkshop?: number; //场景标签  车间
    templateWorkshop?: number; //车间模板
    selectItems?: SelectItemType[];
    addEnable?: ENABLED;
    remark?: string; //备注，可用于添加经纬度，非必要
    longitude?: number; //经度
    latitude?: number; //纬度
    regionCode: string;
  }

  const ruleForm = reactive<RuleForm>({
    name: '',
    seniorScene: '顶级场景',
    code: '',
    sceneCode: '',
    tagCom: [],
    templateCom: [],
    tagWorkshop: undefined,
    templateWorkshop: undefined,
    selectItems: [{ tag: '', template: '' }],
    addEnable: ENABLED.TRUE,
    remark: '',
    longitude: undefined, //经度
    latitude: undefined, //纬度
    regionCode: '',
  });
  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '公司名称不能为空', trigger: 'blur' },
      { min: 1, max: 100, message: '长度在1-100之间', trigger: 'blur' },
    ],

    code: [
      { required: true, message: '公司代码不能为空', trigger: 'blur' },
      { min: 1, max: 100, message: '长度在1-100之间', trigger: 'blur' },
    ],
  });

  const { data: provinceList } = useRequest(getProvinceList);

  //增加空的场景&模板
  const addChange = () => {
    ruleForm.selectItems!.push({
      tag: '',
      template: '',
    });
  };

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

  //删除场景&模板
  const deleScene = (index) => {
    if (ruleForm.selectItems!.length > 1) {
      ElMessageBox.confirm('请确认是否关闭该场景？', '状态关闭', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          ruleForm.selectItems!.splice(index, 1);
        })
        .catch(() => {
          console.log('取消删除物件');
        });
    } else {
      ElMessage.warning({
        message: '无法删除',
      });
    }
  };
  //添加新公司的提交
  const newCompanyAdd = () => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid) => {
      if (!valid) {
        return;
      }

      const selectTags = ruleForm.selectItems?.filter((item) => {
        return item.tag && item.template;
      });

      if (!selectTags?.[0]) {
        ElMessage({
          message: '请选择标签和模板',
          type: 'error',
        });
        return;
      }

      if (props.allCodes.indexOf(ruleForm.code) > -1) {
        ElMessageBox.confirm('场景代码重复，请重新填写', '代码重复', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'error',
        })
          .then(() => {
            // ruleFormCom.code = '';
            console.log('场景代码重复，请重新填写');
          })
          .catch(() => {
            console.log('取消删除物件');
          });
      } else {
        const newComData = {
          name: ruleForm.name,
          code: ruleForm.code,
          status: Number(ruleForm.addEnable),
          isDeleted: 0,
          parentId: 0,
          serial: 0,
          remark: ruleForm.remark,
          longitude: ruleForm.longitude,
          latitude: ruleForm.latitude,
          regionCode: ruleForm.regionCode,
        };
        //提交数据并重置关闭el-draw
        addCompany(newComData)
          .then((res) => {
            //选出不为空字符串的数据
            ruleForm.selectItems = ruleForm.selectItems!.filter((item) => {
              return item.tag && item.template;
            });
            //将selectItems加工成保存公司-模板的数据类型
            const newModuleLabel = ruleForm.selectItems!.map((item) => {
              return {
                companyId: res,
                isDeleted: 0,
                sceneLabelId: Number(item.tag), //item.tag
                sceneModuleId: Number(item.template), ///item.template
              };
            });

            //保存公司-场景标签-场景模板关系
            return addCompanyModuleLabel(newModuleLabel);
          })
          .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;
        }
      }

      ruleForm.selectItems = ruleForm.selectItems!.filter((item) => {
        return item.tag && item.template;
      });
      //新增的数据
      const editNewCom = {
        id: props.detail.id,
        name: ruleForm.name,
        code: ruleForm.code,
        status: Number(ruleForm.addEnable),
        remark: ruleForm.remark,
        longitude: ruleForm.longitude,
        latitude: ruleForm.latitude,
        regionCode: ruleForm.regionCode,
      };
      // 编辑上传
      editCompany(editNewCom)
        .then(() => {
          //保存公司-场景标签-场景模板关系
          const editModuleLabel = ruleForm.selectItems!.map((item) => {
            return {
              companyId: props.detail.id,
              isDeleted: 0,
              sceneLabelId: Number(item.tag), //item.tag
              sceneModuleId: Number(item.template), ///item.template
            };
          });
          return editCompanyModuleLabel(editModuleLabel);
        })
        .finally(() => {
          emit('onOk');
        });
    });
  };

  //重置编辑框
  const resetDrawCom = () => {
    ruleForm.name = '';
    ruleForm.code = '';
    ruleForm.addEnable = ENABLED.TRUE;
    ruleForm.selectItems = [{ tag: '', template: '' }];
    ruleForm.regionCode = '';
  };
</script>

<style scoped></style>
