<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <a-col :span="24">
          <a-form-item label="版本" v-bind="validateInfos.title">
            {{ formData.title }}
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="课程类型" v-bind="validateInfos.twoTitle"> （{{ oldInfo.twoTitle_dictText }}） </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <!-- 
单行文本	1	
多行文本	2	
富文本	3	
固定表单（基础信息）	4	
关联表格	5	
自增单行文本	6	
自增富文本	7	
自增多行文本	8 
自增表格	9 
-->
    <a-row>
      <a-col :span="24" v-for="(item, index) in zyJxdgMainTable.dataSource" :key="index">
        <a-row>
          <a-col :span="24">
            <span class="title">{{ item.title }}</span>
          </a-col>
          <!-- 单行文本	1	 -->
          <a-col v-if="item.type === '1'" :span="24">
            <a-input placeholder="请输入内容" v-model:value="item.content" style="width: 100%"></a-input>
          </a-col>
          <!-- 多行文本	2	 -->
          <a-col v-else-if="item.type === '2'" :span="24">
            <a-textarea placeholder="请输入内容" v-model:value="item.content" style="width: 100%"></a-textarea>
          </a-col>
          <!-- 富文本	3	 -->
          <a-col v-else-if="item.type === '3'" :span="24">
            <j-editor placeholder="请输入内容" v-model:value="item.content" :disabled="disabled" />
          </a-col>
          <!-- 固定表单（基础信息）	4	 -->
          <a-col v-else-if="item.type === '4'" v-model:value="item.content" :span="24">
            <a-form v-bind="formItemLayout">
              <a-row>
                <a-col v-for="(item2, index2) in item.zyJxdgPzxxList" :key="index2" :span="12">
                  <a-form-item :label="item2.title"><a-input :placeholder="`请输入` + item2.title"  v-model:value="item2.content"/></a-form-item>
                  <!-- {{ item2.title }}:<a-input placeholder="请输入内容" style="width:60%;"></a-input>  -->
                </a-col>
              </a-row>
            </a-form>
          </a-col>
          <!-- 自增表格	5	 -->
          <a-col v-else-if="item.type === '5'" :span="24">
            <a-table :columns="getTableColumns(item.zyJxdgPzxxList)" :dataSource="item.list" :pagination="false">
              <template #bodyCell="{ column, record }">
                <a-input placeholder="请输入内容" v-model:value="record[column.key]" style="width: 80%"></a-input>
                <!-- <template v-if="column.key === 'name'">
                </template> -->
              </template>
            </a-table>
          </a-col>
          <!-- 自增单行文本	6	 -->
          <a-col v-else-if="item.type === '6'" :span="24">
            <a-row>
              <a-col>
                <a-button type="primary" @click="handleDhwb(item)">添加</a-button>
              </a-col>
              <a-col v-for="(item2, index2) in item.list" :key="index2">
                <a-input placeholder="请输入内容" v-model:value="item2.title" style="width: 80%" @blur="handleGlxm(item)"></a-input>
                <a-button type="danger" @click="handleDhwbDel(item, index2)">删除</a-button>
              </a-col>
            </a-row>
          </a-col>
          <!-- 自增富文本	7	 -->
          <a-col v-else-if="item.type === '7'" :span="24">
            <a-row>
              <a-col>
                <a-button type="primary" @click="handleDhfwb(item)">添加</a-button>
              </a-col>
              <a-col v-for="(item2, index2) in item.list" :key="index2">
                <j-editor placeholder="请输入内容" v-model:value="item2.title" :disabled="disabled" style="width: 500px; height: 200px" />
                <a-button type="danger" @click="handleDhfwbDel(item, index2)">删除</a-button>
              </a-col>
            </a-row>
          </a-col>
          <!-- 自增多行文本	8  -->
          <a-col v-else-if="item.type === '8'" :span="24">
            <a-row>
              <a-col>
                <a-button type="primary" @click="handleDhwbArea(item)">添加</a-button>
              </a-col>
              <a-col v-for="(item2, index2) in item.list" :key="index2">
                <a-textarea placeholder="请输入内容" v-model:value="item2.title" :disabled="disabled" />
                <a-button type="danger" @click="handleDhwbAreaDel(item, index2)">删除</a-button>
              </a-col>
            </a-row>
          </a-col>

          <!-- 自增表格	9  -->
          <a-col v-else-if="item.type === '9'" :span="24">
            <div><a-button type="primary" @click="handleZzbg(item)">新增</a-button> </div>
            <a-table :columns="getTableZzColumns(item.zyJxdgPzxxList)" :dataSource="item.list" :pagination="false">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                  <a-button type="danger" @click="handleZzbgDel(item.list, record.sort)">删除</a-button>
                </template>
                <template v-else>
                  <a-input placeholder="请输入内容" v-model:value="record[column.key]" style="width: 100%"></a-input>
                </template>
              </template>
            </a-table>
          </a-col>

          <a-col v-else> </a-col>

          <a-col :span="24">
            <span class="tishi">
              {{ item.tsy }}
            </span>
          </a-col>
        </a-row>
      </a-col>
    </a-row>
  </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 { queryZyJxdgMainListByMainId, queryDataById, saveOrUpdate2 } from '../ZyJxdgBanben.api';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { zyJxdgMainColumns } from '../ZyJxdgBanben.data';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import { Form } from 'ant-design-vue';
import JEditor from '/@/components/Form/src/jeecg/components/JEditor.vue';

const useForm = Form.useForm;

export default defineComponent({
  name: 'ZyJxdgBanbenForm',
  components: {
    JDictSelectTag,
    JVxeTable,
    JEditor,
  },
  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 zyJxdgMainTableRef = ref();
    const oldInfo = ref({});
    const zyJxdgMainTable = reactive<Record<string, any>>({
      loading: false,
      columns: zyJxdgMainColumns,
      dataSource: [],
    });
    const activeKey = ref('zyJxdgMain');
    const formData = reactive<Record<string, any>>({
      id: '',
      title: '',
      twoTitle: '',
      sfsy: '',
    });

    //表单验证
    const validatorRules = reactive({});
    const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });
    const dbData = {};
    const formItemLayout = {
      labelCol: { xs: { span: 24 }, sm: { span: 8 } },
      wrapperCol: { xs: { span: 24 }, sm: { span: 13 } },
    };
    const columns = [];

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

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

    async function edit(row) {
      oldInfo.value = row;
      //主表数据
      await queryMainData(row.id);
      //子表数据
      const zyJxdgMainDataList = await queryZyJxdgMainListByMainId(row['id']);
      zyJxdgMainTable.dataSource = [...zyJxdgMainDataList];
    }

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

    const { getSubFormAndTableData, transformData } = useValidateAntFormAndTable(activeKey, {
      zyJxdgMain: zyJxdgMainTableRef,
    });

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

    async function submitForm() {
      const alllist = zyJxdgMainTable.dataSource;
      console.log('✋', alllist);

      var values = {
        id:'',
        rwbh:'202320242000629',
        banbenId:oldInfo.value.id,
        teacherNo:'2002900106',
        sffb:'0',
        list:alllist,
      }
      // const mainData = await getFormData();
      // const subData = zyJxdgMainTable.dataSource;
      // const values = Object.assign({}, dbData, mainData);
      // values.zyJxdgMainList = subData;
      console.log('表单提交数据', values);
      const isUpdate = values.id ? true : false;
      await saveOrUpdate2(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 handleDhwb(item) {
      item.list = item.list || [];
      item.list.push({
        title: '',
        sort: item.list.length + 1,
      });
    }
    //删除单行文本
    function handleDhwbDel(item, index) {
      item.list.splice(index, 1);
      for (var i = 0; i < item.list.length; i++) {
        item.list[i].sort = i;
      }
    }

    //新增多行富文本
    function handleDhfwb(item) {
      item.list = item.list || [];
      item.list.push({
        title: '',
        sort: item.list.length + 1,
      });
    }
    //删除多行富文本
    function handleDhfwbDel(item, index) {
      item.list.splice(index, 1);
      for (var i = 0; i < item.list.length; i++) {
        item.list[i].sort = i;
      }
    }

    //新增多行富文本
    function handleDhwbArea(item) {
      item.list = item.list || [];
      item.list.push({
        title: '',
        sort: item.list.length + 1,
      });
    }
    //删除多行富文本
    function handleDhwbAreaDel(item, index) {
      item.list.splice(index, 1);
      for (var i = 0; i < item.list.length; i++) {
        item.list[i].sort = i;
      }
    }

    //新增自增表格
    function handleZzbg(item) {
      item.list = item.list || [];
      item.list.push({
        title: '',
        sort: item.list.length,
      });
    }
    //删除自增表格
    function handleZzbgDel(list, record) {
      console.log('😁', list, record);
      list.splice(record, 1);
      for (var i = 0; i < list.length; i++) {
        list[i].sort = i;
      }
    }

    //获取列表列表头
    function getTableColumns(list) {
      let columns = reactive<any>([]);
      for (var i = 0; i < list.length; i++) {
        var par = list[i];
        var inePar = {
          title: par.title,
          dataIndex: par.id,
          key: par.id,
        };
        columns.push(inePar);
      }
      return columns;
    }

    //获取自增列表列表头
    function getTableZzColumns(list) {
      let columns = reactive<any>([]);
      for (var i = 0; i < list.length; i++) {
        var par = list[i];
        var inePar = {
          title: par.title,
          dataIndex: par.id,
          key: par.id,
        };
        columns.push(inePar);
      }
      var inePar2 = {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
      };
      columns.push(inePar2);
      return columns;
    }
    //关联项目计算方法
    function handleGlxm(item) {
      console.log('👩‍🍳', item);
      var sfsglxm = item.sfsglxm;
      if (sfsglxm == '1') {
        //判断是否是关联项目
        var list1 = item.list; //课程目标集合
        if (list1 != null) {
          //关联项目是否有值
          var sort = item.sort; //第几个关联项目
          var alllist = zyJxdgMainTable.dataSource; //获取全部的数据
          for (var j = 0; j < alllist.length; j++) {
            for (var i = 0; i < list1.length; i++) {
              var item1 = list1[i];
              var title = item1.title; //具体信息
              var item2 = alllist[j]; //具体数据
              item2.list = item2.list || [];
              if (item2.guanlian == sort) {
                //关联项目等于当前数据
                if (i == 0) {
                  //判断第一回将原来的清空重新赋值
                  item2.list = [];
                }
                //判断当前项是否等于关联项
                var item3 = item2.zyJxdgPzxxList;
                if (item3 != null && item3.length > 0) {
                  item2.list.push({ [item3[0].id]: title });
                }
              }
            }
          }
        }
      }
    }

    return {
      zyJxdgMainTableRef,
      zyJxdgMainTable,
      validatorRules,
      validateInfos,
      activeKey,
      loading,
      formData,
      oldInfo,
      setFieldsValue,
      handleFormChange,
      formItemLayout,
      disabled,
      getFormData,
      submitForm,
      add,
      edit,
      getTableColumns,
      getTableZzColumns,
      columns,
      handleDhwb,
      handleDhwbDel,
      handleDhfwb,
      handleDhfwbDel,
      handleDhwbArea,
      handleDhwbAreaDel,
      handleGlxm,
      handleZzbg,
      handleZzbgDel,
    };
  },
});
</script>
<style scoped lang="less" >
.title {
  margin-left: 20px;
  font-size: 16px;
  font-weight: bold;
}
.tishi {
  width: 100%;
  font-size: 12px;
  color: #fd8f02;
  margin-top: -4px;
  background: #fffbf2;
  text-align: center;
  padding: 6px 0;
}
</style>