<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form class="antd-modal-form" labelAlign="left" v-bind="formItemLayout" name="BgTakepulseForm" ref="formRef">
          <a-row class="form-content-row" :gutter="[12, 4]">
            <a-col :xs="24" :md="12">
              <a-form-item label="年份" v-bind="validateInfos.year" id="BgTakepulseForm-year" name="year">
                <a-date-picker
                  v-model:value="formData.year"
                  picker="year"
                  value-format="YYYY"
                  placeholder="请选择年份"
                  style="width: 100%"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="密级" v-bind="validateInfos.secretLevel" id="BgTakepulseForm-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 :xs="24" :md="12">
              <a-form-item label="序号" v-bind="validateInfos.number" id="BgTakepulseForm-number" name="number">
                <a-input v-model:value="formData.number" placeholder="请输入序号" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="会议类型" v-bind="validateInfos.taskType" id="BgTakepulseForm-taskType" name="taskType">
                <j-dict-select-tag
                  v-model:value="formData.taskType"
                  dictCode="super_takepulse_type"
                  placeholder="请选择会议类型：行政线、技术线"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="类别" v-bind="validateInfos.type" id="BgTakepulseForm-type" name="type">
                <a-input v-model:value="formData.type" placeholder="请输入类别：如党的建设" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="提出人" v-bind="validateInfos.proposer" id="BgTakepulseForm-proposer" name="proposer">
                <!--						<j-select-user v-model:value="formData.proposer"      allow-clear />-->
                <sz-dept-user-modal v-model:value="formData.proposer" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="意见主题" v-bind="validateInfos.title" id="BgTakepulseForm-title" name="title">
                <a-input v-model:value="formData.title" placeholder="请输入意见主题" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="具体意见" v-bind="validateInfos.content" id="BgTakepulseForm-content" name="content">
                <a-textarea v-model:value="formData.content" :rows="4" placeholder="请输入具体意见" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="分管所领导" v-bind="validateInfos.manageSuoleader" id="BgTakepulseForm-manageSuoleader" name="manageSuoleader">
                <RoleUserSelectDropDown v-model:value="formData.manageSuoleader" :roleId="CHARGE_LEADER_ROLE_ID" placeholder="请选择分管所领导" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="责任领导" v-bind="validateInfos.suoleader" id="BgTakepulseForm-suoleader" name="suoleader">
                <sz-dept-user-modal v-model:value="formData.suoleader" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="牵头部门" v-bind="validateInfos.responDeptid" id="BgTakepulseForm-responDeptid" name="responDeptid">
                <sz-select-dept v-model:value="formData.responDeptid" :multiple="true" :checkable="false" checkStrictly allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="协办部门" v-bind="validateInfos.assistDeptid" id="BgTakepulseForm-assistDeptid" name="assistDeptid">
                <sz-select-dept v-model:value="formData.assistDeptid" :multiple="true" :checkable="false" checkStrictly allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="落实部门" v-bind="validateInfos.implementDeptid" id="BgTakepulseForm-implementDeptid" name="implementDeptid">
                <a-input v-model:value="formData.implementDeptid" placeholder="请输入落实部门" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="是否采纳" v-bind="validateInfos.isAdopt" id="BgTakepulseForm-isAdopt" name="isAdopt">
                <j-switch v-model:value="formData.isAdopt"></j-switch>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                class="full-width-aligned-form-item"
                label="落实措施/解释说明"
                v-bind="validateInfos.measure"
                id="BgTakepulseForm-measure"
                name="measure"
                :labelCol="wideLabelCol"
                :wrapperCol="wideWrapperCol"
              >
                <a-textarea v-model:value="formData.measure" :rows="4" placeholder="请输入落实措施/解释说明" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="措施数量" v-bind="validateInfos.measureNumber" id="BgTakepulseForm-measureNumber" name="measureNumber">
                <a-input-number v-model:value="formData.measureNumber" placeholder="请输入措施数量" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                class="full-width-aligned-form-item"
                label="成果形式"
                v-bind="validateInfos.achievement"
                id="BgTakepulseForm-achievement"
                name="achievement"
                :labelCol="wideLabelCol"
                :wrapperCol="wideWrapperCol"
              >
                <a-textarea v-model:value="formData.achievement" :rows="4" placeholder="请输入成果形式" />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="要求完成日期" v-bind="validateInfos.deadline" id="BgTakepulseForm-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 :xs="24" :md="12">
              <a-form-item label="备注" v-bind="validateInfos.remark" id="BgTakepulseForm-remark" name="remark">
                <a-input v-model:value="formData.remark" placeholder="请输入备注" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <!--						<a-col :span="12">-->
            <!--							<a-form-item label="执行情况" v-bind="validateInfos.actualExect" id="BgTakepulseForm-actualExect" name="actualExect">-->
            <!--								<a-textarea v-model:value="formData.actualExect" :rows="4" placeholder="请输入执行情况" />-->
            <!--							</a-form-item>-->
            <!--						</a-col>-->
            <a-col :xs="24" :md="12">
              <a-form-item label="实际完成时间" v-bind="validateInfos.actualTime" id="BgTakepulseForm-actualTime" name="actualTime">
                <a-date-picker
                  placeholder="请选择实际完成时间"
                  v-model:value="formData.actualTime"
                  showTime
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="提出人确认" v-bind="validateInfos.proposerConfirm" id="BgTakepulseForm-proposerConfirm" name="proposerConfirm">
                <a-input v-model:value="formData.proposerConfirm" placeholder="请输入提出人确认" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="完成状态" v-bind="validateInfos.bpmStatus" id="BgTakepulseForm-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="12">-->
            <!--							<a-form-item label="调整落实措施及执行情况" v-bind="validateInfos.actSt" id="BgTakepulseForm-actSt" name="actSt">-->
            <!--								<a-textarea v-model:value="formData.actSt" :rows="4" placeholder="请输入调整落实措施及执行情况" />-->
            <!--							</a-form-item>-->
            <!--						</a-col>-->
            <a-col :xs="24" :md="12">
              <a-form-item label="督办次数" v-bind="validateInfos.superviseCount" id="BgTakepulseForm-superviseCount" name="superviseCount">
                <a-input v-model:value="formData.superviseCount" placeholder="请输入督办次数" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="是否急件" v-bind="validateInfos.urgencyLevel" id="BgTakepulseForm-urgencyLevel" name="urgencyLevel">
                <j-dict-select-tag v-model:value="formData.urgencyLevel" dictCode="yn" placeholder="请选择是否急件" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="是否需要所办负责人审批" v-bind="validateInfos.isNeedAppro" id="BgTakepulseForm-isNeedAppro" name="isNeedAppro">
                <j-switch v-model:value="formData.isNeedAppro"></j-switch>
              </a-form-item>
            </a-col>
            <a-col v-if="showSupDeptLeader" :xs="24" :md="12">
              <a-form-item label="所办负责人" v-bind="validateInfos.supDeptleaderid" id="BgTakepulseForm-supDeptleaderid" name="supDeptleaderid">
                <DeptRoleUserSelectRadioGroup v-model:value="formData.supDeptleaderid" :deptId="SUP_LEADER_DEPT_ID" :roleId="SUP_LEADER_ROLE_ID" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

    <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, watch } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { queryDataById, saveOrUpdate } from '../BgTakepulse.api';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSwitch from '/@/components/Form/src/jeecg/components/JSwitch.vue';
  import SzSelectDept from '/@/components/Form/src/jeecg/components/SzSelectDept.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';
  import DeptRoleUserSelectRadioGroup from '@/components/semri/userComponent/DeptRoleUserSelectRadioGroup.vue';
  import SzDeptUserModal from '@/components/semri/deptUserComponent/SzDeptUserModal.vue';
  import DeptRoleUserSelectDropDown from '@/components/semri/userComponent/DeptRoleUserSelectDropDown.vue';
  import {
    SUOBAN_DEPT_ID,
    MEASURE_RES_LEADER_ROLE_ID,
    PARTY_COMMITTEE_DEPT_ID as CHARGE_LEADER_DEPT_ID,
    CHARGE_LEADER_ROLE_ID,
  } from '/@/constant/supervision';
  import RoleUserSelectDropDown from '@/components/semri/userComponent/RoleUserSelectDropDown.vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: 'BgTakepulseForm',
    components: {
      RoleUserSelectDropDown,
      SzDeptUserModal,
      DeptRoleUserSelectDropDown,
      DeptRoleUserSelectRadioGroup,
      JDictSelectTag,
      JSwitch,
      SzSelectDept,
      JSelectUser,
      JFormContainer,
    },
    props: {
      formDisabled: {
        type: Boolean,
        default: false,
      },
      formData: { type: Object, default: () => {} },
      formBpm: { type: Boolean, default: true },
    },
    emits: ['success'],
    setup(props, { emit }) {
      const SUP_LEADER_DEPT_ID = SUOBAN_DEPT_ID;
      const SUP_LEADER_ROLE_ID = MEASURE_RES_LEADER_ROLE_ID;
      const { createMessage } = useMessage();
      const loading = ref(false);
      const formRef = ref();
      const formData = reactive<Record<string, any>>({
        id: '',
        secretLevel: '',
        year: '',
        number: '',
        taskType: '',
        type: '',
        proposer: '',
        title: '',
        content: '',
        manageSuoleader: '',
        suoleader: '',
        responDeptid: '',
        assistDeptid: '',
        implementDeptid: '',
        isAdopt: '',
        measure: '',
        measureNumber: undefined,
        achievement: '',
        deadline: '',
        remark: '',
        actualExect: '',
        actualTime: '',
        proposerConfirm: '',
        bpmStatus: '1',
        actSt: '',
        superviseCount: '',
        urgencyLevel: '',
        isNeedAppro: '',
        supDeptleaderid: '',
        delFlag: '',
      });

      const showSupDeptLeader = computed(() => formData.isNeedAppro === '1');

      //表单验证
      const validatorRules = reactive({
        year: [{ required: true, message: '请选择年份' }],
        secretLevel: [{ required: true, message: '请选择密级' }],
        title: [{ required: true, message: '请输入意见主题' }],
        responDeptid: [
          { required: true, message: '请选择牵头部门' },
          {
            validator: async (_rule, value) => {
              if (value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)) {
                return Promise.reject('请选择牵头部门');
              }
              return Promise.resolve();
            },
          },
        ],
        supDeptleaderid: [
          {
            validator: async (_rule, value) => {
              if (showSupDeptLeader.value && !value) {
                return Promise.reject('请选择所办领导');
              }
              return Promise.resolve();
            },
          },
        ],
      });
      const { resetFields, validate, validateInfos, clearValidate } = useForm(formData, validatorRules, { immediate: false });
      const dbData = {};
      const formItemLayout = {
        labelCol: { xs: { span: 24 }, sm: { span: 7 } },
        wrapperCol: { xs: { span: 24 }, sm: { span: 17 } },
      };
      const wideLabelCol = { xs: { span: 24 }, sm: { span: 3 } };
      const wideWrapperCol = { xs: { span: 24 }, sm: { span: 21 } };

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

      // 不需要所办领导审批时，隐藏字段不能保留历史选择或校验错误。
      function clearSupDeptLeaderIfNotNeeded() {
        if (!showSupDeptLeader.value) {
          formData.supDeptleaderid = '';
          clearValidate(['supDeptleaderid']);
        }
      }

      watch(() => formData.isNeedAppro, clearSupDeptLeaderIfNotNeeded);

      onMounted(() => {
        initFormData();
      });
      //渲染流程表单数据
      const queryByIdUrl = '/bqtakepulse/bgTakepulse/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];
          });
          clearSupDeptLeaderIfNotNeeded();
        }
      }
      // 是否显示提交按钮
      const showFlowSubmitButton = computed(() => {
        if (props.formBpm === true) {
          if (props.formData.disabled === false) {
            return true;
          }
        }
        return false;
      });

      function add() {
        resetFields();
      }

      async function edit(row) {
        await queryMainData(row.id);
      }

      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);
        clearSupDeptLeaderIfNotNeeded();
      }

      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 normalizeMainFormData(toRaw(formData));
      }

      function normalizeMainFormData(data) {
        if (data) {
          if (data.isNeedAppro !== '1') {
            data.supDeptleaderid = '';
          }
          Object.keys(data).forEach((key) => {
            if (Array.isArray(data[key])) {
              data[key] = data[key].join(',');
            }
          });
        }
        return data;
      }

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

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

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

      return {
        validatorRules,
        validateInfos,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        wideLabelCol,
        wideWrapperCol,
        disabled,
        showSupDeptLeader,
        showFlowSubmitButton,
        CHARGE_LEADER_DEPT_ID,
        CHARGE_LEADER_ROLE_ID,
        SUP_LEADER_DEPT_ID,
        SUP_LEADER_ROLE_ID,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
      };
    },
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;

    :deep(.ant-form-item-label) {
      padding-bottom: 0;
      text-align: left;
    }

    :deep(.ant-form-item-label > label) {
      width: 100%;
      justify-content: flex-start;
    }

    :deep(.ant-form-item-control),
    :deep(.ant-form-item-control-input),
    :deep(.ant-form-item-control-input-content) {
      text-align: left;
    }
  }

  .form-content-row {
    :deep(.ant-form-item) {
      margin-bottom: 6px;
    }

    :deep(.ant-input),
    :deep(.ant-input-affix-wrapper),
    :deep(.ant-input-number),
    :deep(.ant-picker),
    :deep(.ant-select-selector) {
      min-height: 30px;
    }
  }

  // 整行文本框按半行字段的 7/17 栅格折算宽度，确保左右边缘精确对齐。
  @media (min-width: 576px) {
    .full-width-aligned-form-item {
      :deep(.ant-form-item-label) {
        flex: 0 0 14.5833%;
        max-width: 14.5833%;
      }

      :deep(.ant-form-item-control) {
        flex: 0 0 85.4167%;
        max-width: 85.4167%;
      }
    }
  }
</style>
