<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-row>
              <div class="wrapper-back">
                <div class="wrapper-title">基本信息</div>
              <a-col :span="24">
                <a-form-item label="作业题目">
                  {{zyInfo.title}}
                </a-form-item>
              </a-col>
              <a-col :span="24" v-if="dataKhnr.length > 0">
                <a-form-item label="考察内容">
                  <a-table :columns="columnsKhnr" rowKey="id" :data-source="dataKhnr" :pagination="false" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="作业截止时间" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
                  {{zyInfo.endTime}}
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="作业发布时间" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
                  {{zyInfo.startTime}}
                </a-form-item>
              </a-col>
              <a-col :span="24" v-if="zyInfo.content">
                <a-form-item label="作业要求" >
                  <div v-html="zyInfo.content" style="margin-top:5px"></div>
                </a-form-item>
              </a-col>
              <a-col :span="24" v-if="zyInfo.filePath">
                <a-form-item label="参考资料" >
                  <span>{{ lastString(zyInfo.filePath) }}</span>
                  <a-button type="primary" style="margin-left: 10px" @click="downLoad(zyInfo.filePath)">下载</a-button>
                </a-form-item>
              </a-col>

              <a-col :span="24" v-show="zyInfo.sturead=='1' && zyInfo.pfbz">
                <a-form-item label="评分标准" layout="inline">
                    <div v-html="zyInfo.pfbz" style="margin-top: 5px;"></div>
                </a-form-item>
              </a-col>
              </div>
              <a-col :span="24" v-if="zyInfo.wwtgl" class="wrapper-back">
                <div class="wrapper-title">查重设置</div>
                <a-form-item  layout="inline" style="margin-left: 100px">
                  <a-form-item label="检测通过率" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
                    <span style="padding: 7px 7px"></span>
                    <a-input-number
                      v-model:value="zyInfo.wwtgl"
                      placeholder="检测通过率"
                      style="width: 60%"
                      :max="100"
                      :min="0"
                      disabled
                    >
                      <template #addonAfter> % </template>
                    </a-input-number>
                  </a-form-item>
                  <a-form-item label="比对库设置" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
                    <div style="padding: 7px 12px">维普</div>
                    <div style="padding: 0 10px">
                      <a-checkbox v-model:checked="zyInfo.wwcc" style="margin-left: 10px" disabled>
                        <span class="Check-title">维普资源库查重：</span><br>
                        <span class="Check-concent">中文科技期刊数据库、硕博学位论文库、高校特色论文库、互联网数据资源/互联网文档资源</span>
                      </a-checkbox>
                      <a-checkbox v-model:checked="zyInfo.xncc" disabled>
                        <span class="Check-title">学校作业库查重：</span><br>
                        <span class="Check-concent">历届学生提供的作业库内查重</span>
                      </a-checkbox>
                      <a-checkbox v-model:checked="zyInfo.nwcc" disabled>
                        <span class="Check-title"> 本次作业查重：</span><br>
                        <span class="Check-concent">本次学生提交的作业间查重</span>
                      </a-checkbox>
                    </div>
                    <div style="padding: 7px 15px">AIGC</div>
                    <div>
                      <a-checkbox v-model:checked="zyInfo.aigccc" style="margin-left: 20px" disabled>
                        <span class="Check-title">AIGC查重：</span><br>
                        <span class="Check-concent">检测作业是否部分或全部由AI模型生成</span>
                     </a-checkbox>
                    </div>
                  </a-form-item>
                </a-form-item>
              </a-col>
              <a-col :span="24" v-if="!isYl" style="text-align: center; margin-top:20px">
                <div v-if="zyInfo.sfcc == '1'">
                  <j-upload v-model:value="formData.filePath"  :disabled="disabled" maxCount="1" accept=".doc,.docx,.pdf" :text="`上传作业`" style="background: #ededed; " :forceAcceptVerify="true" ></j-upload>
                </div>
                <div v-if="zyInfo.sfcc == '0'">
                  <j-upload v-model:value="formData.filePath"  :disabled="disabled" maxCount="1" :text="`上传作业`" style="background: #ededed; " :forceAcceptVerify="true" ></j-upload>
                </div>
            </a-col>
        <a-col :span="24" v-if="isYl">
          <span style="width:300px;float: left;">
          <span style="float:left;">
            <j-upload v-model:value="formData.stuFilePath" maxCount="1" accept=".doc,.docx,.pdf"  :forceAcceptVerify="true"></j-upload>
          </span>
          </span>
            <span style="float: right;">
            <a-button type="primary" style="margin-left:10px;" @click="openPdf(formData)">预览</a-button>
          </span>
        </a-col>
            </a-row>
          </a-form>
        </a-col>          

        <!-- <a-col :span="24" style="padding:  30px 0 0 75px;">
            <div style="line-height:40px;">作业名称：{{zyInfo.title}}</div>
            <div style="line-height:40px;">作业要求：<span v-html="zyInfo.content?zyInfo.content:'无'"></span></div>
            <div style="line-height:40px;">上传时间：{{zyInfo.startTime}} ~ {{zyInfo.endTime}}</div>
            <div style="line-height:40px;">上传时间：{{zyInfo.startTime}} ~ {{zyInfo.endTime}}</div>
            <div style="line-height:40px;">检测方式：是否网络查重-{{zyInfo.wwcc=='1'?'是':'否'}} ， 是否课程内查重-{{zyInfo.nwcc=='1'?'是':'否'}} ， Aigc是否查重-{{zyInfo.nwcc=='1'?'是':'否'}} ， 是否校内查重-{{zyInfo.xncc=='1'?'是':'否'}} </div>
            <div v-if="zyInfo.filePath">附件：
            <a-button type="primary" style="margin-left: 10px" @click="downLoad(zyInfo.filePath)">下载</a-button></div>
        </a-col> -->
        
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate,zyscStu,stuWpKsjc  } from '../ZyInfoStudent.api';
  import { Form } from 'ant-design-vue';
  import {getFileAccessHttpUrl} from "/@/utils/common/compUtils";
  import {useGlobSetting} from "/@/hooks/setting";

  const globSetting = useGlobSetting();
  const baseApiUrl = globSetting.domainUrl;
  const { createConfirm } = useMessage();
  const dataKhnr = ref<any>([]);

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const isYl = ref<boolean>(false);
  const stuId = ref<string>('');
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok','closeLoading']);
  const formData = reactive<Record<string, any>>({
    id: '',
    filePath: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  let zyInfo = ref<any>({});
  //表单验证
  const validatorRules = {
    filePath: [{ required: true, message: '请上传作业附件!'},],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  const labelCol2 = reactive({
    sm: { span: 10 },
  });
  const wrapperCol2 = reactive({
    sm: { span: 10 },
  });
  const labelCol3 = reactive({
    sm: { span: 4 },
  });
  const wrapperCol3 = reactive({
    sm: { span: 20 },
  });

const columnsKhnr = [
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    customRender: (text) => {
      return text.index + 1;
    },
    width: 80,
  },
  {
    title: '章次',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '节次',
    dataIndex: 'twoTitle',
    key: 'twoTitle',
  },
];

function lastString(record) {
  console.log('😓', record);
  const parts = record.split('/');
  console.log('🧔', parts);
  return parts[parts.length - 1];
}
//选择考察内容
function handleKcnr(kcnr) {
  if(kcnr){
    defHttp.get({ url: '/teachingunitcontent/kcTeachingUnitContentOne/getAllList', params: { id: kcnr } }).then((res) => {
      console.log('🤦‍♀️', res);
      dataKhnr.value = res;
    });
  }else{
    dataKhnr.value = [];
  }
  
}
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  function downLoad(file) {
  if (file) {
    let url = getFileAccessHttpUrl(file);
    if (url) {
      window.open(url);
    }
  } else {
    createMessage.warning('暂无文件或文件上传中');
  }
}
  /**
   * 编辑
   */
  function edit(record) {
    console.log(`🚀 ~ edit ~ record:`, record)
    stuId.value = record.stuId;
    nextTick(() => {
      resetFields();


      defHttp.get({url:'/zyInfo/zyInfo/queryZyinfoByStuId',params:{id:record.id}}).then((res) => {
        console.log(`🚀 ~ defHttp.get ~ res:`, res)
        zyInfo.value = res;
        console.log(`🚀 ~ defHttp.get ~ zyInfo:`, zyInfo)
        
        // handleKcnr(zyInfo.value.kcnr)
      });


      //赋值
      Object.assign(formData, record);
      isYl.value = record.isYl;
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    // var t = await validate();
    
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    if(!model.filePath){
        emit('closeLoading');
        confirmLoading.value = false;
      createMessage.warning("请上传作业附件");
      return;
    }
    createConfirm({
      iconType: 'warning',
      title: '确认提交',
      content: '是否确认提交数据',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        model.stuId = stuId.value;
        model.mainId = zyInfo.value.id;
        zyscStu(model, isUpdate.value)
          .then((res) => {
            console.log(`🚀 ~ .then ~ res:`, res)
            if (res.success) {
              createMessage.success("操作成功");
              emit('ok');
              //异步提交维普
              stuWpKsjc(model, isUpdate.value).then((res) => {})
            } else {
              createMessage.warning(res.message);
            }
            emit('closeLoading');
          })
          .finally(() => {
            confirmLoading.value = false;
            emit('closeLoading');
          });
      },
      onCancel: () => {
        confirmLoading.value = false;
        emit('closeLoading');
      },
    });
  }

  function openPdf(record){
    if(record.stuPdfPath){
      var url2 = getFileAccessHttpUrl(record.stuPdfPath)
      let url = baseApiUrl+"/generic/web/viewer.html?file="+encodeURIComponent(url2);
      window.open(url,"_blank")
    }else{
      createMessage.warning("暂无文件或文件上传中")
    }
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 300px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
  .wrapper-back {
  background: #fafafa;
  border-radius: 10px;
  margin-top: 10px;
  padding-top: 15px;
  width: 100%;
}
.wrapper-title {
  font-size: 18px;
  border-left: 4px solid #1ab394;
  font-weight: bold;
  padding-left: 20px;
  margin-bottom: 20px;
}
.Check-title{
  color: #333;
  font-weight: bold;
}
.Check-concent{
  color: #999;
  font-size: 12px;
}
</style>
