<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="ZjSqxxForm">
          <a-row>
            <a-col :span="24" >
              <a-form-item label="用户" v-bind="validateInfos.userName" id="ZjSqxxForm-userId" name="userName" class="mdule-box">
                <a-input v-model:value="formData.userName" placeholder="请选择用户" allow-clear style="width: 60%" disabled></a-input>
                <a-input v-model:value="formData.userId" placeholder="请选择用户" allow-clear hidden></a-input>
                <a-button type="primary" @click="handleSelect" style="margin-left: 10px"> 选择用户</a-button>
                <a-button type="primary" @click="handleShouquan" style="margin-left: 10px"> 授权</a-button>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-for="(item, index) in sqDataList" :key="index"  class="mdule-box">
            <a-col :span="24">
              <a-form-item label="授权范围" id="ZjSqxxForm-sqfw" name="sqfw">
                <j-dict-select-tag v-model:value="item.sqfw" dictCode="zj_sqfw" placeholder="请选择授权范围" allow-clear style="width:80%" />
                  <a-button type="primary" @click="handleSqDel(index)">删除</a-button>
              </a-form-item>
            </a-col>
            <!-- 过程考核 -->
            <a-col :span="24" v-if="item.sqfw == '0'">
              <a-row>
                <a-col :span="24">
                  <a-form-item label="授权开始时间" id="ZjSqxxForm-sqStartTime" name="sqStartTime">
                    <a-date-picker
                      placeholder="请选择授权开始时间"
                      v-model:value="item.sqStartTime"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="授权结束时间" id="ZjSqxxForm-sqEndTime" name="sqEndTime">
                    <a-date-picker
                      placeholder="请选择授权结束时间"
                      v-model:value="item.sqEndTime"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="学年学期" id="ZjSqxxForm-xnxq" name="xnxq">
                    <j-dict-select-tag v-model:value="item.xnxq" dictCode="xqxn" placeholder="请选择学年学期" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="开课单位" id="ZjSqxxForm-kkdw" name="kkdw">
                    <JSelectMultiple v-model:value="item.kkdw" placeholder="请选择开课单位" :dictCode="`v_kkdw,KKYXMC,KKYXMC`"></JSelectMultiple>
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="24">
                  <a-form-item label="校内专业（大类）" v-bind="validateInfos.zydl" id="ZjSqxxForm-zydl" name="zydl">
                    <a-input v-model:value="item.zydl" placeholder="请输入校内专业（大类）" allow-clear></a-input>
                  </a-form-item>
                </a-col> -->
                <a-col :span="24">
                  <a-form-item label="课程类别" id="ZjSqxxForm-kclb" name="kclb">
                    <JSelectMultiple v-model:value="item.kclb" placeholder="请选择开课单位" dictCode="kcxz"></JSelectMultiple>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="课程名称" id="ZjSqxxForm-kcmc" name="kcmc">
                    <a-input-group compact>
                      <a-input v-model:value="item.kcmc" style="width: calc(100% - 64px)" disabled placeholder="请输入课程名称" />
                      <a-button type="primary" @click="handleKecheng(index)">选择</a-button>
                    </a-input-group>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-col>
            <!-- 智慧教室 -->
            <a-col :span="24" v-if="item.sqfw == '1'">
              <a-row>
                <a-col :span="24">
                  <a-form-item label="授权开始时间" id="ZjSqxxForm-sqStartTime" name="sqStartTime">
                    <a-date-picker
                      placeholder="请选择授权开始时间"
                      v-model:value="item.sqStartTime"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="授权结束时间" id="ZjSqxxForm-sqEndTime" name="sqEndTime">
                    <a-date-picker
                      placeholder="请选择授权结束时间"
                      v-model:value="item.sqEndTime"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="学年学期" id="ZjSqxxForm-xnxq" name="xnxq">
                    <j-dict-select-tag v-model:value="item.xnxq" dictCode="xqxn" placeholder="请选择学年学期" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="开课单位" id="ZjSqxxForm-kkdw" name="kkdw">
                    <JSelectMultiple v-model:value="item.kkdw" placeholder="请选择开课单位" :dictCode="`v_kkdw,KKYXMC,KKYXMC`"></JSelectMultiple>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="课程名称" id="ZjSqxxForm-kcmc" name="kcmc">
                    <a-input-group compact>
                      <a-input v-model:value="item.kcmc" style="width: calc(100% - 64px)" disabled placeholder="请输入课程名称" />
                      <a-button type="primary" @click="handleKecheng(index)">选择</a-button>
                    </a-input-group>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-col>
            <!-- 毕业论文 -->
            <a-col :span="24" v-if="item.sqfw == '2'">
              <a-row>
                <a-col :span="24">
                  <a-form-item label="授权开始时间" id="ZjSqxxForm-sqStartTime" name="sqStartTime">
                    <a-date-picker
                      placeholder="请选择授权开始时间"
                      v-model:value="item.sqStartTime"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="授权结束时间" id="ZjSqxxForm-sqEndTime" name="sqEndTime">
                    <a-date-picker
                      placeholder="请选择授权结束时间"
                      v-model:value="item.sqEndTime"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="毕业年份" id="ZjSqxxForm-xnxq" name="xnxq">
                    <j-dict-select-tag v-model:value="item.xnxq" dictCode="xnxq" placeholder="请选择毕业年份" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="所属院系名称" id="ZjSqxxForm-kkdw" name="kkdw">
                    <JSelectMultiple v-model:value="item.kkdw" placeholder="请选择开课单位" :dictCode="`v_kkdw,KKYXMC,KKYXMC`"></JSelectMultiple>
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="24">
                  <a-form-item label="所属校内专业（大类）名称" v-bind="validateInfos.zydl" id="ZjSqxxForm-zydl" name="zydl">
                    <a-input v-model:value="item.zydl" placeholder="请输入所属校内专业（大类）名称" allow-clear></a-input>
                  </a-form-item>
                </a-col> -->
                <a-col :span="24">
                  <a-form-item label="毕业论文（设计）类别" id="ZjSqxxForm-kcmc" name="kcmc">
                    <JSelectMultiple v-model:value="item.kclb" placeholder="请选择开课单位" dictCode="kcxz"></JSelectMultiple>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-col>
            <!-- 实习实践 -->
            <a-col :span="24" v-if="item.sqfw == '3'">
              <a-row>
                <a-col :span="24">
                  <a-form-item label="学年学期" id="ZjSqxxForm-xnxq" name="xnxq">
                    <j-dict-select-tag v-model:value="item.xnxq" dictCode="xqxn" placeholder="请选择学年学期" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="授权开始时间" id="ZjSqxxForm-sqStartTime" name="sqStartTime">
                    <a-date-picker
                      placeholder="请选择授权开始时间"
                      v-model:value="item.sqStartTime"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="授权结束时间" id="ZjSqxxForm-sqEndTime" name="sqEndTime">
                    <a-date-picker
                      placeholder="请选择授权结束时间"
                      v-model:value="item.sqEndTime"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="开课单位" id="ZjSqxxForm-kkdw" name="kkdw">
                    <JSelectMultiple v-model:value="item.kkdw" placeholder="请选择开课单位" :dictCode="`v_kkdw,KKYXMC,KKYXMC`"></JSelectMultiple>
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="24">
                  <a-form-item label="校内专业（大类）" v-bind="validateInfos.zydl" id="ZjSqxxForm-zydl" name="zydl">
                    <a-input v-model:value="item.zydl" placeholder="请输入校内专业（大类）" allow-clear></a-input>
                  </a-form-item>
                </a-col> -->
                <a-col :span="24">
                  <a-form-item label="课程类别" id="ZjSqxxForm-kclb" name="kclb">
                    <JSelectMultiple v-model:value="item.kclb" placeholder="请选择开课单位" dictCode="kcxz"></JSelectMultiple>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="课程名称" id="ZjSqxxForm-kcmc" name="kcmc">
                    <a-input-group compact>
                      <a-input v-model:value="item.kcmc" style="width: calc(100% - 64px)" disabled placeholder="请输入课程名称" />
                      <a-button type="primary" @click="handleKecheng(index)">选择</a-button>
                    </a-input-group>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
    <!--用户选择弹窗-->
    <UseSelectModal @register="registerModal" @select="selectOk" />
    <KcKetangbiaoCheckModal ref="KcKetangbiaoCheckModalPage" @success="ketangSuccess"></KcKetangbiaoCheckModal>
  </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 JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import { getValueType } from '/@/utils';
import { saveNew } from '../ZjSqxx.api';
import { Form } from 'ant-design-vue';
import { useModal } from '/src/components/Modal';
import UseSelectModal from '/@/views/system/role/components/UseSelectModalNew.vue';
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import JSelectMultiple from '/@/components/Form/src/jeecg/components/JSelectMultiple.vue';
import KcKetangbiaoCheckModal from '/@/views/bl/kcKetangbiao/KcKetangbiaoCheckModal.vue';

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => ({}) },
  formBpm: { type: Boolean, default: true },
});
const formRef = ref();
const KcKetangbiaoCheckModalPage = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  userId: '',
  userName: '',
  zjNo: '',
  zjName: '',
  sqfw: '',
  sqStartTime: '',
  sqEndTime: '',
  xnxq: '',
  zydl: '',
  kcmc: '',
  kkdw: '',
  sqzt: '',
});
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);
const sqDataList = ref<any>([]);
const checkIndex = ref<number>(-1);
//表单验证
const validatorRules = reactive({});
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

//注册drawer
const [registerModal, { openModal }] = useModal();
// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});

function handleSqDel(index){
  sqDataList.value.splice(index, 1);
}

/**
 * 新增
 */
function add() {
  edit({
    zjNo: '',
    zjName: '',
    sqfw: '',
    sqStartTime: '',
    sqEndTime: '',
    xnxq: '',
    zydl: '',
    kcmc: '',
    kkdw: '',
    sqzt: '',
  });
}

/**
 * 编辑
 */
function edit(record) {
  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if (record.hasOwnProperty(key)) {
        tmpData[key] = record[key];
      }
    });
    //赋值
    Object.assign(formData, tmpData);
  });
}
/**
 * 选择课程
 */
function handleKecheng(index) {
  checkIndex.value = index;
  KcKetangbiaoCheckModalPage.value.disabled = false;
  KcKetangbiaoCheckModalPage.value.add();
}
/**
 * 课程回显
 * @param record 
 */
function ketangSuccess(record) {
  console.log('🙍', record);
  var kcmcStr = record.map((item) => item).join(',');
  sqDataList.value[checkIndex.value].kcmc = kcmcStr;
}

/**
 * 授权（新增列表）
 */
function handleShouquan() {
  var list = sqDataList.value;
  list.push({});
}

/**
 * 选择已有用户
 */
function handleSelect() {
  openModal(true);
}
/**
 * 添加已有用户
 */
async function selectOk(val) {
  console.log('👯', val);
  defHttp.post({ url: '/sys/user/getInfoByIds', params: { ids: val.join(',') } }).then((res) => {
    console.log('👱‍♀️', res);
    formData.userId = val.join(',');
    formData.userName = res.userName;
  });
  // await addUserRole({ roleId: roleId.value, userIdList: val }, reload);
}
/**
 * 提交数据
 */
async function submitForm() {
  try {
    // 触发表单验证
    await validate();
  } catch ({ errorFields }) {
    if (errorFields) {
      const firstField = errorFields[0];
      if (firstField) {
        formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
      }
    }
    return Promise.reject(errorFields);
  }
  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(',');
      }
    }
  }
  model.sqDataList = sqDataList.value;
  console.log('💋', model);

  await saveNew(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}

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

<style lang="less" scoped>
.antd-modal-form {
  padding: 14px;
  background: #f7f7f7;
}
.mdule-box{
  border: 2px solid #ececec;
  background: #fff;
  border-radius:8px;
  margin:0 10px 10px 10px;
  padding:20px 0;
}
.mdule-box:hover{
  border: 2px solid #ececec;
  background: #fff;
  border-radius:8px;
  box-shadow: 1px 1px 10px 1px #dedede;
  cursor: pointer;
}
</style>
