<script setup lang="ts">
import { computed, ref, watchEffect, reactive, unref } from "vue";
import { ActionType } from "/@/components/PageContent";
import { createBasicTitle } from "./utils/create-basic-title";
import { ElForm, ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { projectFormRules } from "../config/_rules";
import { ComCard } from "/@/components/RemoteSelect";
import { STATUS_OPTIONS } from "/@/config/status";
import LadderTable from "./ladder-table.vue";
import LadderModal from "./ladder-modal.vue";
import { useNav } from "/@/layout/hooks/useNav";
import OrderDialog from "/@/components/PageListModal";
const { logout } = useNav();
import { httpAdd, httpDetail, httpUpdate } from "/@/api/operate/setTheme";
const ladderModalRef = ref<InstanceType<typeof LadderModal>>(null);
const modelRef = ref<InstanceType<typeof OrderDialog>>(null);
const emit = defineEmits(["submitOk"]);
const ruleFormRef = ref<FormInstance>();
const form = {
  id: "",
  group_id: "",
  code: "",
  modular1_type: "1",
  modular1_status: "1",
  modular1_title: "轮播区",
  modular1_data: [],
  modular2_type: "2",
  modular2_status: "1",
  modular2_title: "产品宣传",
  modular2_data: [],
  modular3_type: "3",
  modular3_status: "1",
  modular3_title: "产品展示",
  modular3_data: [],
  modular4_type: "4",
  modular4_status: "1",
  modular4_title: "产品优势",
  modular4_data: []
};
const ruleForm = reactive({ ...form });
const basicFormRef = ref<InstanceType<typeof ElForm>>(null);

const type = ref<ActionType>("preview");
const dialogVisible = ref(false);
const confirmLoading = ref(false);
const title = ref("");
const uID = ref("");

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (confirmLoading.value) return;

      confirmLoading.value = true;
      const { id, group_id, code } = ruleForm;
      const model = {
        id,
        group_id,
        code,
        modular: []
      };
      for (let i = 1; i < 5; i++) {
        let modela = {
          type: ruleForm[`modular${i}_type`],
          status: ruleForm[`modular${i}_status`],
          title: i < 3 ? "" : ruleForm[`modular${i}_title`],
          data: ruleForm[`modular${i}_data`]
        };
        // const data = JSON.parse(JSON.stringify(modela.data))
        // da
        model.modular.push(modela);
      }
      let res = {};
      if (type.value == "create") {
        delete model["id"];
        res = await httpAdd(model);
      } else {
        res = await httpUpdate(model);
      }
      const { code: hcode, data, message } = res;
      confirmLoading.value = false;
      if (hcode === 0) {
        dialogVisible.value = false;
        emit("submitOk", {});
      } else if (hcode >= 100 && hcode <= 104) {
        logout();
      } else {
        ElMessage.warning(message);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

async function handlePush(_ladder, index, type) {
  console.log(ruleForm);
  ruleForm[`modular${type}_data`].push(_ladder);
}

function modularShow() {
  if (!ruleForm.group_id) return ElMessage.warning("请选择公司卡类型！");
  modelRef.value.show("");
}
async function handleUpdate(_ladder, index, type) {
  ruleForm[`modular${type}_data`][index] = _ladder;
}
function handleAddOrder(list) {
  console.log(list);
  list.forEach(item => {
    const { id } = item;
    let findex = ruleForm.modular3_data.findIndex(e => e.id + "" == id + "");
    if (findex == -1) {
      let model = Object.assign(item, {
        img: item.good_cover_img,
        good_id: item.id,
        jump_type: "2",
        jump_param: `/good?id=${item.id}`,
        style_type: "",
        title: ""
      });
      ruleForm.modular3_data.push(model);
    }
  });
}
const initData = async () => {
  if (confirmLoading.value) return;
  confirmLoading.value = true;
  const { code, data, message } = await httpDetail({ id: uID.value });
  if (code === 0) {
    const { id, code, group_id, modular } = data;
    ruleForm.id = id;
    ruleForm.code = code;
    ruleForm.group_id = group_id;
    modular.forEach(item => {
      const { type } = item;
      ruleForm[`modular${type}_type`] = type + "";
      ruleForm[`modular${type}_status`] = item?.status + "" || "";
      ruleForm[`modular${type}_title`] = item?.title + "" || "";
      ruleForm[`modular${type}_data`] = item?.data || [];
    });
  } else if (code >= 100 && code <= 104) {
    logout();
  } else {
    ElMessage.warning(message);
  }
  confirmLoading.value = false;
};
defineExpose({
  onShow: async (basicTitle: string, readonly: ActionType, id: string) => {
    type.value = readonly;
    const readTitle = createBasicTitle(type.value);
    title.value =
      readonly == "preview" ? basicTitle + readTitle : readTitle + basicTitle;
    Object.keys(ruleForm).forEach(key => {
      ruleForm[key] = form[key];
    });
    dialogVisible.value = true;
    confirmLoading.value = false;
    uID.value = id;
    if (type.value !== "create") {
      await initData();
    }
  }
});
</script>

<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    center
    top="5vh"
    destroy-on-close
    width="1024px"
  >
    <el-form
      ref="ruleFormRef"
      v-loading="confirmLoading"
      :model="ruleForm"
      :rules="projectFormRules"
      label-width="100px"
      :disabled="type === 'preview'"
      status-icon
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="主题编号" prop="code">
            <el-input v-model="ruleForm.code" placeholder="主题编号" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="公司卡类型" prop="group_id">
            <ComCard v-model="ruleForm.group_id" placeholder="公司卡类型" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-row>
            <el-col :span="8">
              <el-form-item label="轮播区域" prop="modular1_status">
                <el-select
                  v-model="ruleForm.modular1_status"
                  placeholder="是否使用"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in STATUS_OPTIONS"
                    :label="item.label"
                    :value="item.id"
                    :key="item.id + index"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item
                label="数据"
                label-width="60px"
                prop="modular1_data"
              >
                <LadderTable
                  :readonly="type === 'preview'"
                  :type="1"
                  :ladder="ruleForm.modular1_data"
                  @delete="index => ruleForm.modular1_data.splice(index, 1)"
                  @choose="() => ladderModalRef.onDisplay(0, '1')"
                  @update="
                    ({ data, index }) =>
                      ladderModalRef.onDisplay(index, '1', data)
                  "
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>

        <el-col :span="24">
          <el-row>
            <el-col :span="8">
              <el-form-item label="产品宣传" prop="modular2_status">
                <el-select
                  v-model="ruleForm.modular2_status"
                  style="width: 100%"
                  placeholder="是否使用"
                >
                  <el-option
                    v-for="(item, index) in STATUS_OPTIONS"
                    :label="item.label"
                    :value="item.id"
                    :key="item.id + index"
                  />
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="区域名称" prop="modular2_title">
                <el-input v-model="ruleForm.modular2_title" />
              </el-form-item> -->
            </el-col>
            <el-col :span="16">
              <el-form-item
                label="数据"
                label-width="60px"
                prop="modular2_data"
              >
                <LadderTable
                  :readonly="type === 'preview'"
                  :type="2"
                  :ladder="ruleForm.modular2_data"
                  @delete="index => ruleForm.modular2_data.splice(index, 1)"
                  @choose="() => ladderModalRef.onDisplay(0, '2')"
                  @update="
                    ({ data, index }) =>
                      ladderModalRef.onDisplay(index, '2', data)
                  "
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="24">
          <el-row>
            <el-col :span="8">
              <el-form-item label="产品展示" prop="modular3_status">
                <el-select
                  v-model="ruleForm.modular3_status"
                  style="width: 100%"
                  placeholder="是否使用"
                >
                  <el-option
                    v-for="(item, index) in STATUS_OPTIONS"
                    :label="item.label"
                    :value="item.id"
                    :key="item.id + index"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="区域名称" prop="modular3_title">
                <el-input
                  v-model="ruleForm.modular3_title"
                  placeholder="区域名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item
                label="数据"
                label-width="60px"
                prop="modular3_data"
              >
                <LadderTable
                  :readonly="type === 'preview'"
                  :type="3"
                  :ladder="ruleForm.modular3_data"
                  @delete="index => ruleForm.modular3_data.splice(index, 1)"
                  @choose="() => modularShow()"
                  @update="
                    ({ data, index }) =>
                      ladderModalRef.onDisplay(index, '3', data)
                  "
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="24">
          <el-row>
            <el-col :span="8">
              <el-form-item label="产品优势" prop="modular4_status">
                <el-select
                  v-model="ruleForm.modular4_status"
                  style="width: 100%"
                  placeholder="是否使用"
                >
                  <el-option
                    v-for="(item, index) in STATUS_OPTIONS"
                    :label="item.label"
                    :value="item.id"
                    :key="item.id + index"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="区域名称" prop="modular4_title">
                <el-input
                  v-model="ruleForm.modular4_title"
                  placeholder="区域名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item
                label="数据"
                label-width="60px"
                prop="modular4_data"
              >
                <LadderTable
                  :readonly="type === 'preview'"
                  :type="4"
                  :ladder="ruleForm.modular4_data"
                  @delete="index => ruleForm.modular4_data.splice(index, 1)"
                  @choose="() => ladderModalRef.onDisplay(0, '4')"
                  @update="
                    ({ data, index }) =>
                      ladderModalRef.onDisplay(index, '4', data)
                  "
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <el-form-item v-if="type !== 'preview'">
        <div class="w-full flex justify-end">
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >提交</el-button
          >
          <ElButton @click="() => (dialogVisible = false)">取消</ElButton>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
  <LadderModal ref="ladderModalRef" @update="handleUpdate" @push="handlePush" />
  <OrderDialog ref="modelRef" @save-btn-click="handleAddOrder" />
</template>
