<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="ImprovementProposalForm" ref="formRef">
          <a-row>
						<a-col :span="12">
							<a-form-item label="提案编号" v-bind="validateInfos.proposalNo" id="ImprovementProposalForm-proposalNo" name="proposalNo">
								<a-input v-model:value="formData.proposalNo" placeholder="请输入提案编号"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="提案名称" v-bind="validateInfos.proposalName" id="ImprovementProposalForm-proposalName" name="proposalName">
								<a-input v-model:value="formData.proposalName" placeholder="请输入提案名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="提出日期" v-bind="validateInfos.proposalDate" id="ImprovementProposalForm-proposalDate" name="proposalDate">
								<a-date-picker placeholder="请选择提出日期"  v-model:value="formData.proposalDate" value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="提案部门ID" v-bind="validateInfos.proposalDeptId" id="ImprovementProposalForm-proposalDeptId" name="proposalDeptId">
								<a-input v-model:value="formData.proposalDeptId" placeholder="请输入提案部门ID"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="提案部门名称" v-bind="validateInfos.proposalDeptName" id="ImprovementProposalForm-proposalDeptName" name="proposalDeptName">
								<a-input v-model:value="formData.proposalDeptName" placeholder="请输入提案部门名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="申请人ID" v-bind="validateInfos.applicantId" id="ImprovementProposalForm-applicantId" name="applicantId">
								<a-input v-model:value="formData.applicantId" placeholder="请输入申请人ID"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="申请人姓名" v-bind="validateInfos.applicantName" id="ImprovementProposalForm-applicantName" name="applicantName">
								<a-input v-model:value="formData.applicantName" placeholder="请输入申请人姓名"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="团队名称" v-bind="validateInfos.teamName" id="ImprovementProposalForm-teamName" name="teamName">
								<a-input v-model:value="formData.teamName" placeholder="请输入团队名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="提案类别" v-bind="validateInfos.proposalCategory" id="ImprovementProposalForm-proposalCategory" name="proposalCategory">
								<a-input v-model:value="formData.proposalCategory" placeholder="请输入提案类别"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="问题描述" v-bind="validateInfos.problemDesc" id="ImprovementProposalForm-problemDesc" name="problemDesc">
								<a-textarea v-model:value="formData.problemDesc" :rows="4" placeholder="请输入问题描述" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="改善方法及措施" v-bind="validateInfos.improvementMethod" id="ImprovementProposalForm-improvementMethod" name="improvementMethod">
								<a-textarea v-model:value="formData.improvementMethod" :rows="4" placeholder="请输入改善方法及措施" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="改善前情况描述" v-bind="validateInfos.beforeDesc" id="ImprovementProposalForm-beforeDesc" name="beforeDesc">
								<a-textarea v-model:value="formData.beforeDesc" :rows="4" placeholder="请输入改善前情况描述" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="改善后情况描述" v-bind="validateInfos.afterDesc" id="ImprovementProposalForm-afterDesc" name="afterDesc">
								<a-textarea v-model:value="formData.afterDesc" :rows="4" placeholder="请输入改善后情况描述" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="改善效果" v-bind="validateInfos.improvementEffect" id="ImprovementProposalForm-improvementEffect" name="improvementEffect">
								<a-textarea v-model:value="formData.improvementEffect" :rows="4" placeholder="请输入改善效果" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="最终奖项" v-bind="validateInfos.finalAward" id="ImprovementProposalForm-finalAward" name="finalAward">
								<a-input v-model:value="formData.finalAward" placeholder="请输入最终奖项" disabled allow-clear ></a-input>
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

		<!-- 新增申请只填写主表，子表由后续评分和投票流程维护。 -->
    <a-tabs v-if="showSubTables" v-model:activeKey="activeKey" animated style="overflow:hidden;">
      <a-tab-pane tab="部门评议评分表" key="improvementDeptScore" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="improvementDeptScoreTableRef"
          :loading="improvementDeptScoreTable.loading"
          :columns="improvementDeptScoreTable.columns"
          :dataSource="improvementDeptScoreTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
      <a-tab-pane tab="所级评议投票表" key="improvementInstituteVote" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="improvementInstituteVoteTableRef"
          :loading="improvementInstituteVoteTable.loading"
          :columns="improvementInstituteVoteTable.columns"
          :dataSource="improvementInstituteVoteTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
    </a-tabs>
    <div v-if="showFlowSubmitButton" :span="24" style="width: 100%;text-align: center;margin-top: 10px">
      <a-button preIcon="ant-design:check-outlined" style="width: 126px" type="primary" @click="submitForm">提 交</a-button>
    </div>
  </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 { queryImprovementDeptScoreListByMainId, queryImprovementInstituteVoteListByMainId, queryDataById, saveOrUpdate } from '../ImprovementProposal.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {improvementDeptScoreColumns, improvementInstituteVoteColumns} from '../ImprovementProposal.data';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "ImprovementProposalForm",
    components:{
      JVxeTable,
			JFormContainer,
    },
    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 formRef = ref();
      const improvementDeptScoreTableRef = ref();
      const improvementDeptScoreTable = reactive<Record<string, any>>({
        loading: false,
        columns: improvementDeptScoreColumns,
        dataSource: []
      });
      const improvementInstituteVoteTableRef = ref();
      const improvementInstituteVoteTable = reactive<Record<string, any>>({
        loading: false,
        columns: improvementInstituteVoteColumns,
        dataSource: []
      });
      const activeKey = ref('improvementDeptScore');
      const formData = reactive<Record<string, any>>({
        id: '',
        proposalNo: '',   
        proposalName: '',   
        proposalDate: '',   
        proposalDeptId: '',   
        proposalDeptName: '',   
        applicantId: '',   
        applicantName: '',   
        teamName: '',   
        proposalCategory: '',   
        problemDesc: '',   
        improvementMethod: '',   
        beforeDesc: '',   
        afterDesc: '',   
        improvementEffect: '',   
        finalAward: '',   
      });

      //表单验证
      const validatorRules = reactive({
        proposalNo: [{ required: true, message: '请输入提案编号!'},],
        proposalName: [{ required: true, message: '请输入提案名称!'},],
        proposalDate: [{ required: true, message: '请输入提出日期!'},],
        proposalDeptId: [{ required: true, message: '请输入提案部门ID!'},],
        proposalDeptName: [{ required: true, message: '请输入提案部门名称!'},],
        applicantId: [{ required: true, message: '请输入申请人ID!'},],
        applicantName: [{ required: true, message: '请输入申请人姓名!'},],
        proposalCategory: [{ required: true, message: '请输入提案类别!'},],
        problemDesc: [{ required: true, message: '请输入问题描述!'},],
        improvementMethod: [{ required: true, message: '请输入改善方法及措施!'},],
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      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;
      });

      // 普通新增没有业务 ID，不展示评分和投票子表；已有数据及流程表单正常展示。
      const showSubTables = computed(() => Boolean(formData.id || props.formData?.dataId));

      onMounted(()=>{
        initFormData();
      });
      //渲染流程表单数据
      const queryByIdUrl = '/improvementproposal/improvementProposal/queryById';
      async function initFormData(){
        if(props.formBpm === true){
          let params = {id: props.formData.dataId};
          const row = await defHttp.get({url: queryByIdUrl, params});
          //设置表单的值
          Object.keys(row).map(k => {
            formData[k] = row[k];
          });
          //子表数据
          const improvementDeptScoreDataList = await queryImprovementDeptScoreListByMainId(row['id']);
          improvementDeptScoreTable.dataSource = [...improvementDeptScoreDataList];
          const improvementInstituteVoteDataList = await queryImprovementInstituteVoteListByMainId(row['id']);
          improvementInstituteVoteTable.dataSource = [...improvementInstituteVoteDataList];
        }
      }
      // 是否显示提交按钮
      const showFlowSubmitButton = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return true
          }
        }
        return false
      });
      

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

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const improvementDeptScoreDataList = await queryImprovementDeptScoreListByMainId(row['id']);
        improvementDeptScoreTable.dataSource = [...improvementDeptScoreDataList];
        const improvementInstituteVoteDataList = await queryImprovementInstituteVoteListByMainId(row['id']);
        improvementInstituteVoteTable.dataSource = [...improvementInstituteVoteDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        resetFields();
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }
        })
        //赋值
        Object.assign(formData,tmpData);
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'improvementDeptScore': improvementDeptScoreTableRef,
        'improvementInstituteVote': improvementInstituteVoteTableRef,
      });

      async function getFormData() {
        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);
        }
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const isUpdate = Boolean(mainData.id);
        const values = Object.assign({}, dbData, mainData);
        // 新增提案只保存主表；已有提案编辑或流程提交时才采集子表数据。
        if (isUpdate) {
          const subData = await getSubFormAndTableData();
          Object.assign(values, subData);
        }
        console.log('表单提交数据', values)
        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;
      }


      return {
        improvementDeptScoreTableRef,
        improvementDeptScoreTable,
        improvementInstituteVoteTableRef,
        improvementInstituteVoteTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        showSubTables,
        showFlowSubmitButton,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
      }
    }
  });
</script>
<style lang="less" scoped>
  .ant-tabs-tabpane.sub-one-form {
    max-height: 340px;
    overflow: auto;
  }
</style>
