<template>
  <div id="siteMain">
    <div id="maxSite">
      <a-layout v-show="isAdd">
        <!-- 页头 -->
        <headerPage/>
        <!-- 主体部分 -->
        <a-layout-content>
          <a-card>
            <template #title>
              <div style="text-align: center; font-size: 24px;font-weight: bold;">
                <!-- 听课足迹{{ $route.query.ktId }}-{{ $route.query.type }} -->
                  <span v-if="$route.query.type == '4'">东北师范大学本科课堂教学质量评价表（同行专家用）</span>
                  <span v-else-if="$route.query.type == '3'">东北师范大学听课记录表</span>
                  <span v-else-if="$route.query.type == '2'">线上教学课堂看课、听课评价表</span>
              </div>
              <div style="text-align: center; font-size: 16px;font-weight: bold;font-weight: 400;line-height: 1;color: #777;">
                <!-- 学院名，课程名，授课教师 -->
                {{ form.kcmc }}-{{ form.kkdw }}-{{ form.skjs }}
                <!-- kcmc,kkdw,skjs -->
              </div>
            </template>
            <div style="text-align: left;font-size: 1rem;font-weight: 700;margin: 1rem;">
              <span v-if="$route.query.type == '4'">该评价表是专门为该课程方面的专家/教师听课研制的评价表，更能反映该课堂的教学质量。</span>
              <span v-else-if="$route.query.type == '3'">该评价表是方便行政人员和非该课程所属学科的教师听课使用的评价表，主要用来反映课堂教学的整体情况。</span>
              <span v-else-if="$route.query.type == '2'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;该评价表是根据线上课堂的特点研制的，如果您听的是线上课堂，请您填写该评价表；如果您同时是该课程所属学科的专家/教师，也欢迎您同时填写《同行评价表》。</span>
            </div>
            <div style="padding: 0 15rem;font-weight: 700;">
              <a-row :gutter="[16,16]">
                <a-col :span="24" v-for="(item,index) in list" :key="index">
                  <template v-if="item.isrequire != 0"><span style="color:red;">*</span></template>
                  {{ index + 1 }}.{{ item.content }}
                  <a-row>
                    <template v-if="item.quetype == 3">
                      <a-col :span="24">
                        <a-textarea v-model:value="selectedMap[item.id]"></a-textarea>
                      </a-col>
                    </template>
                    <template v-else-if="item.quetype == 1">
                      <a-radio-group v-model:value="selectedMap[item.id]">
                        <a-col :span="24" v-for="(ans,ansIndex) in item.list" :key="ansIndex">
                          <a-radio :value="ans.id">
                            （{{ ansIndex + 1 }}）{{ ans.content }}
                          </a-radio>
                        </a-col>
                      </a-radio-group>
                    </template>
                    <template v-else-if="item.quetype == 2">
                      <a-checkbox-group v-model:value="selectedMap[item.id]">
                        <a-col :span="24" v-for="(ans,ansIndex) in item.list" :key="ansIndex">
                          <a-checkbox :value="ans.id">
                            （{{ ansIndex + 1 }}）{{ ans.content }}
                          </a-checkbox>
                        </a-col>
                      </a-checkbox-group>
                    </template>

                    <!-- <a-col :span="24" v-for="(ans,ansIndex) in item.list" :key="ansIndex">
                      <template v-if="item.quetype == 1">
                        单选
                      </template>
                      <template v-if="item.quetype == 2">
                        多选
                      </template>
                      （{{ ansIndex + 1 }}）{{ ans.content }}
                    </a-col> -->
                  </a-row>
                </a-col>
              </a-row>
            </div>
            <div style="text-align: center;padding-top: 1rem;">
              <a-button type="primary" style="margin-right: 1rem;" :loading="confirmLoading">取消</a-button>
              <a-button type="primary" @click="save" :loading="confirmLoading">提交</a-button>
            </div>
            <!-- <div>
              {{ selectedMap }}
            </div> -->
            <!--<div style="border:#777;">
              {{ list }}
            </div> -->
          </a-card>
        </a-layout-content>
        <!-- 页尾 -->
        <footerPage/>
      </a-layout>
      <div v-show="!isAdd">
        <div style="text-align: center;height: calc(100vh);">
          <div style="padding: 5rem;font-size: 1.1rem;" class="wenZiJiaCu">
            <p>
              提交成功
            </p>
            <p>
              您的评价对于我们很重要，感谢您的参与。
            </p>
            <p>
              您可以关闭本页，或点击下方按钮打开主页
            </p>
            <p>
              <a-button type="primary" :loading="confirmLoading"><RouterLink to="/site/index">返回首页</RouterLink></a-button>
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from 'vue';
import headerPage from '/@/views/site/common/header.vue';
import footerPage from '/@/views/site/common/footer.vue';
import { defHttp } from '/@/utils/http/axios';
import { useRoute } from 'vue-router'
import { useMessage } from '/@/hooks/web/useMessage';
import { getUserId } from '/@/views/site/utils';

enum Api {
  queryById = '/ktgl/kcKetangbiao/queryById',
  que = '/qa/kcEvaluationque/list',
  ans = '/qa/kcEvaluationans/list',
  save = '/qa/kcEvaluation/addQaAll',
}

const form = ref<any>({});
const list = ref<any>([]);
const selectedMap = ref<any>({});

const confirmLoading = ref<boolean>(false);
const isAdd = ref<boolean>(true);
const { createMessage } = useMessage();

const route = useRoute();
onMounted(() => {
  console.log(route.query );
  let params = { pageSize: -1, status: 0, column: 'ordernum', order: 'asc' }
  let queryQue = defHttp.get({ url: Api.que, params: { ...params, evaluationver: route.query.type } });
  let queryAns = defHttp.get({ url: Api.ans, params });

  Promise.all([queryQue,queryAns]).then(([resQue, resAns]) => {
    let queList = resQue?.records;
    let ansList = resAns?.records;
    let queMap = {}
    queList.forEach(x => {
      // x.list = [];
      queMap[x.id] = x;
      selectedMap.value[x.id] = '';
    });
    ansList.forEach(x => {
      let data = queMap[x.queid];
      if(data){
        let list = data.list;
        if(!list){
          list = [];
          queMap[x.queid].list = list;
        }
        list.push(x);
      }
    });
    list.value = queList;
  });
  defHttp.get({ url: Api.queryById, params: { id: route.query.ktId } }).then(res => {
    form.value = res;
  });
});

function genAns(x,data,isArray): Array<Object> {
  let textanscontent,ansid,queid,upuserid,ketangbiaoid;
  if(isArray){
    let rList = Array<Object>();
    data.forEach(x2 => {
      rList.push(...genAns(x,x2,false))
    })
    return rList;
  }else{
    queid = x.id;
    ansid = data;
    if(x.quetype == 3){
      textanscontent = data;
      ansid = 0;
    }
    upuserid = getUserId();
    ketangbiaoid = route.query.ktId;
    return [{ textanscontent,ansid,queid,upuserid,ketangbiaoid }];
  }
}

function save() {
  confirmLoading.value = true;
  console.log('selectedMap ->',selectedMap);
  let $selectedMap = Object.assign({},selectedMap.value);
  let formData = {
    evaluationver: route.query.type,
    upuserid: getUserId(),
    minkcid: route.query.ktId,
    ansList: Array<Object>()
  };
  //验证
  let errorMsg = '';
  list.value.forEach(x => {
    if(x.isrequire != 0){
      let data = $selectedMap[x.id];
      if(data){
        if(Array.isArray(data)){
          if(!data.length){
            errorMsg = '有必填选项未填写，请检查后重新提交。';
          }else{
            formData.ansList.push(...genAns(x,data,true))
          }
        }else{
          formData.ansList.push(...genAns(x,data,false))
        }
      }else{
        // errorMsg = '有必填选项未填写，请检查后重新提交。'+x.id+'-'+x.content + data;
        errorMsg = '有必填选项未填写，请检查后重新提交。';
      }
    }else{
      //非必填收集数据
      let data = $selectedMap[x.id];
      if(data){
        if(Array.isArray(data)){
          if(data.length){
            formData.ansList.push(...genAns(x,data,true))
          }
        }else{
          formData.ansList.push(...genAns(x,data,false))
        }
      }
    }
  });
  if(errorMsg){
    confirmLoading.value = false
    createMessage.warning(errorMsg);
    return;
  }
  console.log('formData =>',formData);
  //保存
  defHttp.post({ url: Api.save, params: formData }, { isTransformResponse: false })
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        // emit('ok');
        isAdd.value = false;
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });


  // setTimeout(() => {
  //   confirmLoading.value = false
  // },5000)

}


</script>
<style lang="less" scoped>
#siteMain {
  // font-size: ;
  // height: 100%;
  background: #f3f3f4;
  #maxSite {
    //最大宽度
    max-width: 1170px;
    //居中
    margin: 0 auto;
    .rowGutter{
      margin-top: 1rem;
      margin-bottom: 1rem;
    }

    .ant-layout-header {
      color: #fff;
      background: #1ab394;
    }
    .ant-layout-footer {
      line-height: 1.5;
      background: #FFF;
    }
    .ant-layout-sider {
      color: #fff;
      line-height: 120px;
      background: #3ba0e9;
    }
    .ant-layout-content {
      min-height: 120px;
      color: #000;
      line-height: 120px;
      background: #f3f3f4;
    }
    .dictBox :deep(.ant-select) {
      width: 100%;
    }
  }

}
/**暗黑模式特殊配色*/
[data-theme='dark'] #siteMain #maxSite {
  .ant-layout-header, .ant-layout-footer {
    background: #6aa0c7;
  }
  .ant-layout-content {
    background: #107bcb;
  }
  .ant-layout-sider {
    background: #3499ec;
  }
}
.wenZiJiaCu {
  font-weight: 700;
}
a {
  color: #337ab7;
}
</style>