<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <draggable @end="end" v-model="tiganData" item-key="id">
        <template #item="{ index, element: item }">
          <div>
            <!-- 单选题 -->
            <div style="width: 100%" v-if="item.wjType == 3 || item.wjType == '3'">
              <a-card>
                <template #title>
                  <span>{{ index + 1 }}、</span>
                  <a-textarea
                    placeholder="请填写单选题题干"
                    v-model:value="item.wjTitle"
                    :bordered="false"
                    :style="{ width: handinpwei(item.wjTitle) }"
                    :auto-size="{ minRows: 1, maxRows: 5 }"
                    :disabled="editDisabled"
                  />
                  <span style="color: #c2bfbf">[单选]</span>
                </template>
                <template #extra>
                  <a-tooltip placement="topLeft" title="题目分数" v-if="isShow">
                    <a-select
                      style="width: 120px"
                      v-model:value="item.wjScore"
                      placeholder="请选择分数"
                      v-if="item.wjSfqh == '0'"
                      :disabled="editDisabled"
                    >
                      <a-select-option value="5">5</a-select-option>
                      <a-select-option value="4">4</a-select-option>
                      <a-select-option value="3">3</a-select-option>
                      <a-select-option value="2">2</a-select-option>
                      <a-select-option value="1">1</a-select-option>
                    </a-select>
                    <span v-if="item.wjSfqh == '0'" @click="handleQiehuan(item, '1')" style="color: #9e9e9e" :disabled="editDisabled"
                      >自定义分数</span
                    >
                    <a-input-number
                      v-model:value="item.wjScore"
                      style="width: 120px"
                      v-if="item.wjSfqh == '1'"
                      :disabled="editDisabled"
                    ></a-input-number>
                    <span v-if="item.wjSfqh == '1'" @click="handleQiehuan(item, '0')" style="color: #9e9e9e" :disabled="editDisabled">返回</span>
                  </a-tooltip>
                  <a-tooltip placement="topRight" title="删除此题"
                    ><Icon
                      icon="ant-design:delete-outlined"
                      style="cursor: pointer; font-size: 20px; margin: 10px"
                      @click="handleDelTigan(item, index)"
                      v-if="!editDisabled"
                  /></a-tooltip>
                </template>
                <a-row v-if="isShow">
                  <a-col :span="24" style="color: darkgrey; font-size: 13px"> 注：选中即为正确答案 </a-col>
                </a-row>
                <a-radio-group v-model:value="item.itemSelected" style="width: 100%" size="default" :disabled="!isShow">
                  <div style="width: 100%" v-for="(tmxx, index) in item.wjxWjxxTmxxList" :key="index">
                    <a-radio :value="tmxx.itemIndex + ``" style="width: 100%">
                      <a-input
                        placeholder="请填写选项"
                        v-model:value="tmxx.itemTitle"
                        :style="{ width: handinpwei(tmxx.itemTitle) }"
                        :bordered="false"
                        :disabled="editDisabled"
                      />
                      <span style="color: #ecb646" v-if="item.itemSelected == tmxx.itemIndex">(正确答案)</span>
                      <a-tooltip placement="topLeft" title="在下方添加新的选项"
                        ><Icon
                          icon="ant-design:plus-circle-outlined"
                          style="cursor: pointer; margin: 5px; font-size: 20px; color: #1890ff"
                          @click="handleAddTmxx(tmxx, index, item.wjxWjxxTmxxList)"
                          v-if="!editDisabled"
                      /></a-tooltip>
                      <a-tooltip placement="topLeft" title="删除选项"
                        ><Icon
                          icon="ant-design:minus-circle-outlined"
                          style="cursor: pointer; margin: 5px; font-size: 20px; color: #1890ff"
                          @click="handleRemTmxx(tmxx, index, item.wjxWjxxTmxxList)"
                          v-if="!editDisabled"
                      /></a-tooltip>
                    </a-radio>
                  </div>
                </a-radio-group>
              </a-card>
            </div>
            <!-- 多选题 -->
            <div style="width: 100%" v-else-if="item.wjType == 4 || item.wjType == '4'">
              <a-card>
                <template #title>
                  <span>{{ index + 1 }}、</span
                  ><a-textarea
                    placeholder="请填写多选题题干"
                    v-model:value="item.wjTitle"
                    :bordered="false"
                    :style="{ width: handinpwei(item.wjTitle) }"
                    :auto-size="{ minRows: 1, maxRows: 5 }"
                    :disabled="editDisabled"
                  />
                  <span style="color: #c2bfbf">[多选]</span>
                </template>
                <template #extra>
                  <a-tooltip placement="topLeft" title="题目分数" v-if="isShow">
                    <a-select
                      style="width: 120px"
                      v-model:value="item.wjScore"
                      placeholder="请选择分数"
                      v-if="item.wjSfqh == '0'"
                      :disabled="editDisabled"
                    >
                      <a-select-option value="5">5</a-select-option>
                      <a-select-option value="4">4</a-select-option>
                      <a-select-option value="3">3</a-select-option>
                      <a-select-option value="2">2</a-select-option>
                      <a-select-option value="1">1</a-select-option>
                    </a-select>
                    <span v-if="item.wjSfqh == '0'" @click="handleQiehuan(item, '1')" style="color: #9e9e9e" :disabled="editDisabled"
                      >自定义分数</span
                    >
                    <a-input-number
                      v-model:value="item.wjScore"
                      style="width: 120px"
                      v-if="item.wjSfqh == '1'"
                      :disabled="editDisabled"
                    ></a-input-number>
                    <span v-if="item.wjSfqh == '1'" @click="handleQiehuan(item, '0')" style="color: #9e9e9e" :disabled="editDisabled">返回</span>
                  </a-tooltip>
                  <a-tooltip placement="topRight" title="删除此题"
                    ><Icon
                      icon="ant-design:delete-outlined"
                      style="cursor: pointer; font-size: 20px; margin: 10px"
                      @click="handleDelTigan(item, index)"
                      v-if="!editDisabled"
                  /></a-tooltip>
                </template>
                <a-row v-if="isShow">
                  <a-col :span="24" style="color: darkgrey; font-size: 13px"> 注：选中即为正确答案 </a-col>
                </a-row>
                <a-checkbox-group v-model:value="item.itemSelected" style="width: 100%" :disabled="!isShow" @change="handleChecked">
                  <a-row>
                    <a-col :span="24" v-for="(tmxx, index) in item.wjxWjxxTmxxList" :key="index">
                      <!-- -{{item.itemSelected}}-{{tmxx.itemIndex}} -->
                      <a-checkbox :value="tmxx.itemIndex"
                        ><a-input
                          placeholder="请填写选项"
                          v-model:value="tmxx.itemTitle"
                          :bordered="false"
                          :style="{ width: handinpwei(tmxx.itemTitle) }"
                          :disabled="editDisabled"
                      /></a-checkbox>
                      <span style="color: #ecb646" v-if="cheGrp(item.itemSelected, tmxx.itemIndex)">(正确答案)</span>
                      <a-tooltip placement="topLeft" title="在下方添加新的选项"
                        ><Icon
                          icon="ant-design:plus-circle-outlined"
                          style="cursor: pointer; margin: 5px; font-size: 20px; color: #1890ff"
                          @click="handleAddTmxx(tmxx, index, item.wjxWjxxTmxxList)"
                          v-if="!editDisabled"
                      /></a-tooltip>
                    </a-col>
                  </a-row>
                </a-checkbox-group>
              </a-card>
            </div>
            <!-- 填空题 -->
            <div style="width: 100%" v-else-if="item.wjType == 5 || item.wjType == '5'">
              <a-card>
                <template #title>
                  <span>{{ index + 1 }}、</span
                  ><a-textarea
                    placeholder="请填写填空题题干"
                    v-model:value="item.wjTitle"
                    :bordered="false"
                    :style="{ width: handinpwei(item.wjTitle) }"
                    :auto-size="{ minRows: 1, maxRows: 5 }"
                    :disabled="editDisabled"
                  />
                  <span style="color: #c2bfbf">[填空]</span>
                </template>
                <template #extra>
                  <a-tooltip placement="topLeft" title="题目分数" v-if="isShow">
                    <a-select
                      style="width: 120px"
                      v-model:value="item.wjScore"
                      placeholder="请选择分数"
                      v-if="item.wjSfqh == '0'"
                      :disabled="editDisabled"
                    >
                      <a-select-option value="5">5</a-select-option>
                      <a-select-option value="4">4</a-select-option>
                      <a-select-option value="3">3</a-select-option>
                      <a-select-option value="2">2</a-select-option>
                      <a-select-option value="1">1</a-select-option>
                    </a-select>
                    <span v-if="item.wjSfqh == '0'" @click="handleQiehuan(item, '1')" style="color: #9e9e9e" :disabled="editDisabled"
                      >自定义分数</span
                    >
                    <a-input-number
                      v-model:value="item.wjScore"
                      style="width: 120px"
                      v-if="item.wjSfqh == '1'"
                      :disabled="editDisabled"
                    ></a-input-number>
                    <span v-if="item.wjSfqh == '1'" @click="handleQiehuan(item, '0')" style="color: #9e9e9e" :disabled="editDisabled">返回</span>
                  </a-tooltip>
                </template>
                <a-row v-if="isShow">
                  <a-col :span="24">
                    <a-textarea
                      placeholder="请填写答案"
                      v-model:value="item.wjAnswer"
                      :bordered="false"
                      style="width: 100%"
                      :auto-size="{ minRows: 1, maxRows: 5 }"
                      :disabled="editDisabled"
                    />
                  </a-col>
                </a-row>
              </a-card>
            </div>
            <!-- 文件上传 -->
            <div style="width: 100%" v-else-if="item.wjType == 8 || item.wjType == '8'">
              <a-card>
                <template #title>
                  <span>{{ index + 1 }}、</span>
                  <a-textarea
                    placeholder="请填写文件上传题题干"
                    v-model:value="item.wjTitle"
                    :bordered="false"
                    :style="{ width: handinpwei(item.wjTitle) }"
                    :auto-size="{ minRows: 1, maxRows: 5 }"
                    :disabled="editDisabled"
                  />
                  <span style="color: #c2bfbf">[文件上传]</span>
                </template>
                <template #extra>
                  <a-tooltip placement="topLeft" title="题目分数" v-if="isShow">
                    <a-select
                      style="width: 120px"
                      v-model:value="item.wjScore"
                      placeholder="请选择分数"
                      v-if="item.wjSfqh == '0'"
                      :disabled="editDisabled"
                    >
                      <a-select-option value="5">5</a-select-option>
                      <a-select-option value="4">4</a-select-option>
                      <a-select-option value="3">3</a-select-option>
                      <a-select-option value="2">2</a-select-option>
                      <a-select-option value="1">1</a-select-option>
                    </a-select>
                    <span v-if="item.wjSfqh == '0'" @click="handleQiehuan(item, '1')" style="color: #9e9e9e" :disabled="editDisabled"
                      >自定义分数</span
                    >
                    <a-input-number
                      v-model:value="item.wjScore"
                      style="width: 120px"
                      v-if="item.wjSfqh == '1'"
                      :disabled="editDisabled"
                    ></a-input-number>
                    <span v-if="item.wjSfqh == '1'" @click="handleQiehuan(item, '0')" style="color: #9e9e9e" :disabled="editDisabled">返回</span>
                  </a-tooltip>
                </template>
              </a-card>
            </div>

            <div v-else></div>
          </div>
        </template>
      </draggable>
    </a-form>

    <!-- 子表单区域 -->
    <!-- <a-tabs v-model:activeKey="activeKey" animated v-if="!formData.wjAnswer">
      <a-tab-pane tab="选项信息2" key="wjxWjxxTmxx" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="wjxWjxxTmxxTableRef"
          :loading="wjxWjxxTmxxTable.loading"
          :columns="wjxWjxxTmxxTable.columns"
          :dataSource="wjxWjxxTmxxTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="false"
          :toolbar="false">
          </j-vxe-table>
      </a-tab-pane>
    </a-tabs> -->
  </a-spin>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
import { queryWjxWjxxTmxxListByMainId, queryDataById, saveOrUpdate } from '../WjxWjxxTmlb.api';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { wjxWjxxTmxxColumns, wjxWjdcColumns } from '../WjxWjxxTmlb.data';
import { useMessage } from '/@/hooks/web/useMessage';
import { Form } from 'ant-design-vue';
import draggable from 'vuedraggable';
const useForm = Form.useForm;

export default defineComponent({
  name: 'WjxWjxxTmlbForm',
  components: {
    JVxeTable,
    draggable,
  },
  props: {
    formDisabled: {
      type: Boolean,
      default: false,
    },
    formData: { type: Object, default: () => {} },
    formBpm: { type: Boolean, default: true },
  },
  emits: ['success'],
  setup(props, { emit }) {
    const loading = ref(false);
    const wjxWjxxTmxxTableRef = ref();
    const activeKey = ref('wjxWjxxTmxx');
    const isShow = ref<boolean>(true);
    const editDisabled = ref<boolean>(true);
    const tiganData = ref<any>([]);
    const { createConfirm, createMessage, createWarningModal } = useMessage();
    const formData = reactive<Record<string, any>>({
      id: '',
      wjTitle: '',
      wjScore: '',
    });
    const wjxWjxxTmxxTable = reactive<Record<string, any>>({
      loading: false,
      columns: wjxWjxxTmxxColumns,
      dataSource: [],
    });
    //表单验证
    const validatorRules = reactive({});
    const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });
    const dbData = {};
    const formItemLayout = {
      labelCol: { xs: { span: 24 }, sm: { span: 5 } },
      wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
    };

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

    function add() {
      resetFields();
      wjxWjxxTmxxTable.dataSource = [];
    }

    async function edit(row, formDisabled) {
      console.log('😺', formDisabled.value);
      console.log('😰', row);
      editDisabled.value = formDisabled.value;

      defHttp.get({ url: '/wjxWjxxTmlb/wjxWjxxTmlb/getTmxxByTmlbid', params: { id: row.id } }).then((res) => {
        console.log('👦', res);
        tiganData.value = res;
      });

      // //主表数据
      // await queryMainData(row.id);
      // //子表数据
      // const wjxWjxxTmxxDataList = await queryWjxWjxxTmxxListByMainId(row['id']);
      // wjxWjxxTmxxTable.dataSource = [...wjxWjxxTmxxDataList];
    }

    async function queryMainData(id) {
      const row = await queryDataById(id);
      Object.keys(row).map((k) => {
        formData[k] = row[k];
      });
    }

    const { getSubFormAndTableData, transformData } = useValidateAntFormAndTable(activeKey, {
      wjxWjxxTmxx: wjxWjxxTmxxTableRef,
    });

    async function getFormData() {
      await validate();
      return transformData(toRaw(formData));
    }

    async function submitForm() {
      const mainData = await getFormData();
      const subData = await getSubFormAndTableData();
      const values = Object.assign({}, dbData, mainData, subData);
      console.log('表单提交数据', values);
      const isUpdate = values.id ? true : false;
      await saveOrUpdate(values, isUpdate);
      //关闭弹窗
      emit('success');
    }

    function setFieldsValue(values) {
      if (values) {
        Object.keys(values).map((k) => {
          formData[k] = values[k];
        });
      }
    }

    /**
     * 值改变事件触发-树控件回调
     * @param key
     * @param value
     */
    function handleFormChange(key, value) {
      formData[key] = value;
    }

    function handleChecked(record) {
      record = record + '';
    }
    /**
     * 拖动结束事件
     * @param evt
     */
    function end(evt) {
      // for (var i = 0; i < tiganData.value.length; i++) {
      //   tiganData.value[i].wjIndex = i + 1;
      // }
    }

    function cheGrp(a, b) {
      var retChe = false;
      if (a) {
        for (var i = 0; i < a.length; i++) {
          if (a[i] == b) {
            retChe = true;
            break;
          }
        }
      }

      return retChe;
    }
    //添加选项
    function handleAddTmxx(record, index, list) {
      var itemIndex = 0;
      for (var i = 0; i < list.length; i++) {
        var lssx = list[i].itemIndex;
        if (itemIndex < parseInt(lssx)) {
          itemIndex = lssx;
        }
      }

      list.push({ itemTitle: null, itemIndex: parseInt(itemIndex) + 1 });
    }

    //删除选项
    function handleRemTmxx(record, index, list) {
      if (list.length <= 2) {
        createMessage.error('至少保留两个选项');
      } else {
        list.splice(index, 1);
      }
    }
    //计算输入框宽度
    function handinpwei(value) {
      if (!value) {
        return '20rem';
      } else {
        if (String(value).length * 1.1 < 20) {
          return '20rem';
        } else if (String(value).length * 1.1 > 60) {
          return '60rem';
        } else {
          return String(value).length * 1.1 + 'rem';
        }
      }
    }
    //切换题目分数类型
    function handleQiehuan(record, type) {
      console.log(`🚀 ~ handleQiehuan ~ type:`, type);
      console.log(`🚀 ~ handleQiehuan ~ record:`, record);
      record.wjSfqh = type;
    }

    return {
      wjxWjxxTmxxTableRef,
      wjxWjxxTmxxTable,
      validatorRules,
      validateInfos,
      activeKey,
      loading,
      formData,
      setFieldsValue,
      handleFormChange,
      formItemLayout,
      disabled,
      getFormData,
      submitForm,
      add,
      edit,
      handinpwei,
      handleQiehuan,
      handleAddTmxx,
      handleRemTmxx,
      cheGrp,
      end,
      handleChecked,
      isShow,
      tiganData,
      editDisabled,
    };
  },
});
</script>