<template>
  <div class="AddBuildingBox">
    <PageHeader :title="userid ? '编辑问卷' : '添加问卷'"></PageHeader>
    <div class="AddBuildingBody">
      <el-form class="formBody" label-position="right" label-width="130px">
        <el-card>
          <template #header>
            <span>基本信息</span>
          </template>
          <el-row>
            <el-col :span="12">
              <el-form-item label="参与范围" prop="cardName">
                <div class="flex flex-items-center">
                  <el-radio-group v-model="form.scope">
                    <el-radio v-for="item in com_questionnaire_scope" :value="item.value" :label="item.label" :key="item.value"></el-radio>
                  </el-radio-group>
                  <Holder v-if="form.scope === '1'" returnvalue="id" ref="HolderRef" :isMultiple="true" :userid="checkoutUses" @change="handleSelect">
                    <template #default>
                      <el-button type="primary" link @click="OpenUseTablesFun">选择业主</el-button>
                    </template>
                  </Holder>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="时间范围" prop="timeData">
                <el-date-picker
                  v-model="timeData"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  type="datetimerange"
                  range-separator="到"
                  start-placeholder="开始日期时间"
                  end-placeholder="结束日期时间"
                  placeholder="请选择问卷时间范围"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input :rows="5" maxlength="200" show-word-limit type="textarea" placeholder="请输入" v-model="form.remark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="mt-20px">
          <template #header>
            <span>问卷题目</span>
          </template>
          <QuestionnaireEdit ref="questionnaireEditRef" :initial-data="editData" @cancel="handleCancel" @save="handleSave" @publish="handlePublish" />
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import Holder from '@/components/Holder/index.vue';
import QuestionnaireEdit from './components/QuestionnaireEdit.vue';

import PageHeader from '@/components/Pageheader/index.vue';
import { QuestionComponentnaireForm } from '@/api/system/Questionnaire/type';
import { addQuestionnaire, getQuestionnaire, updateQuestionnaire } from '@/api/system/Questionnaire';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { com_questionnaire_scope } = toRefs<any>(proxy?.useDict('com_questionnaire_scope'));

const router = useRouter();
const route = useRoute();

const form = ref({
  scope: '0',
  residents: '',
  remark: ''
});
const timeData = ref([]);
//  ! 路由参数 --------------------------------------------------------------------------------
// 打开
const HolderRef = ref<InstanceType<typeof Holder>>();
function OpenUseTablesFun() {
  HolderRef.value.open(form.value.residents.split(',').filter((item) => item));
}
// 多选
const checkoutUses = ref([]);
function handleSelect(val) {
  checkoutUses.value = val;
  form.value.residents = val
    .map((item: string) => item)
    .filter((item: string) => item)
    .join(',');
}

// ! 编辑问卷  ------------------------------------------------------------------------
const questionnaireEditRef = ref<InstanceType<typeof QuestionnaireEdit>>();
const editData = ref<QuestionComponentnaireForm>(null);

//  ! 路由参数 --------------------------------------------------------------------------------
const userid = ref(null);

onMounted(() => {
  if (route.query.id) {
    userid.value = route.query.id;
    handleEdit(userid.value);
  } else {
    handleAdd();
  }
});
// 新增问卷
function handleAdd() {
  editData.value = null;
  questionnaireEditRef.value?.reset();
}
// 编辑问卷
function handleEdit(id: string | number) {
  // 父组件自己调用接口获取数据
  getQuestionnaire(id).then((res) => {
    editData.value = res.data as QuestionComponentnaireForm;
    editData.value.content = JSON.parse(res.data.content as string);
    questionnaireEditRef.value?.init(res.data as QuestionComponentnaireForm);
    form.value = {
      scope: res.data.scope,
      residents: res.data.residents,
      remark: res.data.remark
    };
    checkoutUses.value = res.data.residents
      .split(',')
      .filter((item) => item)
      .map((item) => item);
    timeData.value = [res.data.startTime, res.data.endTime];
  });
}

// 保存草稿
async function handleSave(data: QuestionComponentnaireForm) {
  try {
    // 父组件自己调用接口提交
    if (userid.value !== null) {
      await updateQuestionnaire({
        ...data,
        content: JSON.stringify(data.content),
        status: '0', // 草稿状态
        startTime: timeData.value[0],
        endTime: timeData.value[1],
        ...form.value
      });
    } else {
      await addQuestionnaire({
        ...data,
        content: JSON.stringify(data.content),
        status: '0', // 草稿状态
        startTime: timeData.value[0],
        endTime: timeData.value[1],
        ...form.value
      });
    }
    ElMessage.success('保存成功');
    handleCancel();
  } catch (e) {
    // 错误处理
    console.log(e);
  }
}

// 发布问卷
async function handlePublish(data: QuestionComponentnaireForm) {
  try {
    if (userid.value !== null) {
      await updateQuestionnaire({
        ...data,
        content: JSON.stringify(data.content),
        status: '1', // 发布状态
        startTime: timeData.value[0],
        endTime: timeData.value[1],
        ...form.value
      });
    } else {
      await addQuestionnaire({
        ...data,
        content: JSON.stringify(data.content),
        status: '1', // 发布状态
        endTime: timeData.value[1],
        startTime: timeData.value[0],
        ...form.value
      });
    }
    ElMessage.success('发布成功');
    handleCancel();
  } catch (e) {
    // 错误处理
  }
}
// 取消
function handleCancel() {
  // 跳转到列表页或关闭弹窗
  router.push('/repair/Questionnaire');
}
</script>

<style scoped lang="scss">
.AddBuildingBox {
  padding: 15px;
  height: 100%;
  width: 100%;
  overflow: hidden;
  overflow-y: auto;
}
.AddBuildingBody {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;

  position: relative;

  .formBody {
    .checkoutSideUsesBox {
      margin-left: 130px;
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 10px;
      li {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 35px;
        font-size: 14px;
        padding: 0 10px;
        line-height: 35px;
        margin-bottom: 10px;
        background-color: #f3f9ff;
        border: 1px solid #8fc0f1;

        @media (max-width: 2000px) {
          font-size: 12px;
        }
        @media (max-width: 1650px) {
          font-size: 10px;
        }
        @media (max-width: 1650px) {
          font-size: 8px;
        }
        .el-icon {
          cursor: pointer;
          &:hover {
            color: red;
          }
        }
        &.add {
          cursor: pointer;
          justify-content: center;
          color: #409eff;
          border: 1px dashed #409eff;
          background-color: transparent;
          &:hover {
            background-color: #40a0ff10;
          }
          span {
            margin-left: 10px;
          }
        }
      }
    }

    &:deep(.el-form-item__content, .el-select, .el-input) {
      width: 350px !important;
      margin-right: 10px;
      .el-cascader {
        width: 100%;
      }
    }
    .el-form-item {
      margin-bottom: 20px;
      align-items: center;
    }
    .el-button {
      width: 100px;
      height: 35px;
      margin-right: 20px;
    }
  }
}
</style>
