<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="DqInspectTaskForm" ref="formRef">
          <a-row>
						<a-col :span="24">
							<a-form-item label="具体问题ID" v-bind="validateInfos.problemId" id="DqInspectTaskForm-problemId" name="problemId">
								<a-input v-model:value="formData.problemId" placeholder="请输入具体问题ID"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="密级" v-bind="validateInfos.secretLevel" id="DqInspectTaskForm-secretLevel" name="secretLevel">
								<j-dict-select-tag v-model:value="formData.secretLevel" dictCode="secret_level" placeholder="请选择密级"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="整改措施" v-bind="validateInfos.improveMeasure" id="DqInspectTaskForm-improveMeasure" name="improveMeasure">
								<a-input v-model:value="formData.improveMeasure" placeholder="请输入整改措施"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="完成时限" v-bind="validateInfos.deadline" id="DqInspectTaskForm-deadline" name="deadline">
								<a-date-picker placeholder="请选择完成时限"  v-model:value="formData.deadline" value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="目标节点" v-bind="validateInfos.targetNode" id="DqInspectTaskForm-targetNode" name="targetNode">
								<a-input v-model:value="formData.targetNode" placeholder="请输入目标节点"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="措施责任领导" v-bind="validateInfos.measureResLeader" id="DqInspectTaskForm-measureResLeader" name="measureResLeader">
						<j-select-user v-model:value="formData.measureResLeader"      allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="措施责任部门" v-bind="validateInfos.measureResDept" id="DqInspectTaskForm-measureResDept" name="measureResDept">
								<j-select-dept v-model:value="formData.measureResDept"       :multiple="true" checkStrictly  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="整改交付成果" v-bind="validateInfos.rectificationEvidence" id="DqInspectTaskForm-rectificationEvidence" name="rectificationEvidence">
								<a-input v-model:value="formData.rectificationEvidence" placeholder="请输入整改交付成果"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="成效评价标准" v-bind="validateInfos.evaluationCriterion" id="DqInspectTaskForm-evaluationCriterion" name="evaluationCriterion">
								<a-input v-model:value="formData.evaluationCriterion" placeholder="请输入成效评价标准"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="是否需要党群领导审批" v-bind="validateInfos.isNeedAppro" id="DqInspectTaskForm-isNeedAppro" name="isNeedAppro">
								<j-dict-select-tag type='radio' v-model:value="formData.isNeedAppro" dictCode="yn" placeholder="请选择是否需要党群领导审批"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="党群领导" v-bind="validateInfos.supDeptleaderid" id="DqInspectTaskForm-supDeptleaderid" name="supDeptleaderid">
						<j-select-user v-model:value="formData.supDeptleaderid"      allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="检查情况" v-bind="validateInfos.inspectionStatus" id="DqInspectTaskForm-inspectionStatus" name="inspectionStatus">
								<a-input v-model:value="formData.inspectionStatus" placeholder="请输入检查情况"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="监督意见" v-bind="validateInfos.supervisoryOpinion" id="DqInspectTaskForm-supervisoryOpinion" name="supervisoryOpinion">
								<a-input v-model:value="formData.supervisoryOpinion" placeholder="请输入监督意见"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="措施数量" v-bind="validateInfos.measureCount" id="DqInspectTaskForm-measureCount" name="measureCount">
								<a-input-number v-model:value="formData.measureCount" placeholder="请输入措施数量" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="流程实例ID" v-bind="validateInfos.bpmProcessId" id="DqInspectTaskForm-bpmProcessId" name="bpmProcessId">
								<a-input v-model:value="formData.bpmProcessId" placeholder="请输入流程实例ID"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="流程状态" v-bind="validateInfos.bpmStatus" id="DqInspectTaskForm-bpmStatus" name="bpmStatus">
								<j-dict-select-tag v-model:value="formData.bpmStatus" dictCode="super_status" placeholder="请选择流程状态"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="整改状态" v-bind="validateInfos.taskStatus" id="DqInspectTaskForm-taskStatus" name="taskStatus">
								<a-input v-model:value="formData.taskStatus" placeholder="请输入整改状态"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="督办次数" v-bind="validateInfos.superviseCount" id="DqInspectTaskForm-superviseCount" name="superviseCount">
								<a-input v-model:value="formData.superviseCount" placeholder="请输入督办次数"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="排序" v-bind="validateInfos.sortNo" id="DqInspectTaskForm-sortNo" name="sortNo">
								<a-input-number v-model:value="formData.sortNo" placeholder="请输入排序" style="width: 100%" />
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated style="overflow:hidden;">
      <a-tab-pane tab="工作进展反馈" key="dqInspectProgress" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="dqInspectProgressTableRef"
          :loading="dqInspectProgressTable.loading"
          :columns="dqInspectProgressTable.columns"
          :dataSource="dqInspectProgressTable.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 { queryDqInspectProgressListByMainId, queryDataById, saveOrUpdate } from '../DqInspectTask.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {dqInspectProgressColumns} from '../DqInspectTask.data';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSelectDept from '/@/components/Form/src/jeecg/components/JSelectDept.vue';
  import JSelectUser from '/@/components/Form/src/jeecg/components/JSelectUser.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "DqInspectTaskForm",
    components:{
      JDictSelectTag,
      JSelectDept,
      JSelectUser,
      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 dqInspectProgressTableRef = ref();
      const dqInspectProgressTable = reactive<Record<string, any>>({
        loading: false,
        columns: dqInspectProgressColumns,
        dataSource: []
      });
      const activeKey = ref('dqInspectProgress');
      const formData = reactive<Record<string, any>>({
        id: '',
        problemId: '',   
        secretLevel: '',   
        improveMeasure: '',   
        deadline: '',   
        targetNode: '',   
        measureResLeader: '',   
        measureResDept: '',   
        rectificationEvidence: '',   
        evaluationCriterion: '',   
        isNeedAppro: '',   
        supDeptleaderid: '',   
        inspectionStatus: '',   
        supervisoryOpinion: '',   
        measureCount: undefined,
        bpmProcessId: '',   
        bpmStatus: '',   
        taskStatus: '',   
        superviseCount: '',   
        sortNo: undefined,
        delFlag: '',   
      });

      //表单验证
      const validatorRules = reactive({
      });
      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;
      });

      onMounted(()=>{
        initFormData();
      });
      //渲染流程表单数据
      const queryByIdUrl = '/dqinspecttask/dqInspectTask/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 dqInspectProgressDataList = await queryDqInspectProgressListByMainId(row['id']);
          dqInspectProgressTable.dataSource = [...dqInspectProgressDataList];
        }
      }
      // 是否显示提交按钮
      const showFlowSubmitButton = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return true
          }
        }
        return false
      });
      

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

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const dqInspectProgressDataList = await queryDqInspectProgressListByMainId(row['id']);
        dqInspectProgressTable.dataSource = [...dqInspectProgressDataList];
      }

      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, {
        'dqInspectProgress': dqInspectProgressTableRef,
      });

      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 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;
      }


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