<template>
  <BasicModal
    width="1200px"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :useWrapper="true"
    :minHeight="500"
  >
    <div class="process-cofig">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 2 }"
        :wrapper-col="{ span: 4 }"
        style="height: 100%"
      >
        <div class="info-item info-item-basic">
          <div class="title">基本信息</div>
          <div class="form-continer">
            <a-form-item label="业务类型" name="type">
              <a-select
                v-model:value="formState.type"
                placeholder="请选择业务类型"
                :disabled="getTitle === '查看流程配置'"
              >
                <template v-for="item in dicBusiness" :key="item.value">
                  <a-select-option :value="item.value">{{ item.label }}</a-select-option>
                </template>
              </a-select>
            </a-form-item>
          </div>
        </div>
        <div class="info-item info-item-steps">
          <div class="title">步骤配置</div>
          <div class="form-continer">
            <div class="left-continer">
              <a-table
                v-if="formState.steps.length > 0"
                bordered
                rowKey="xh"
                :data-source="formState.steps"
                :columns="pColumns"
                :pagination="false"
                :customRow="customRow"
                style="height: 100%"
              >
                <template #operation="{ record }">
                  <a style="color: #2d74e7" @click="editStep(record)">编辑</a>
                </template>
              </a-table>
            </div>
            <div class="right-continer">
              <add-step-form
                :currStep="currStep"
                @editStep="updateStep"
                @reduceStep="reduceStep"
              ></add-step-form>
            </div>
          </div>
        </div>
      </a-form>
    </div>
  </BasicModal>
</template>
<script lang="ts">
import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface';
import {
  defineComponent,
  ref,
  computed,
  unref,
  reactive,
  onMounted,
  UnwrapRef,
  toRaw,
  nextTick,
} from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { accountFormSchema, accountFormSchema2, busType, stepColumns } from './configData';
import { useMessage } from '/@/hooks/web/useMessage';
import AddStepForm from './addStepForm.vue';
interface StepInfo {
  xh: number;
  name: string;
  model: string;
  dept: string[];
  user: string[];
}
interface FormState {
  type: string;
  steps: StepInfo[];
}
export default defineComponent({
  name: 'AccountModal',
  components: {
    BasicModal,
    BasicForm,
    AddStepForm,
  },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const formRef = ref();
    let show1 = ref(true);
    const isUpdate = ref(true);
    const rowId = ref('');
    const postData = ref(null);
    const formState: UnwrapRef<FormState> = reactive({
      type: '',
      steps: ref([{ xh: 1, name: '', model: 'update', dept: [], user: [] }]),
    });
    const rules = {
      type: [{ required: true, message: '请选择业务类型', trigger: 'change' }],
      steps: [{ required: true, message: '请配置审核步骤', trigger: 'change', type: 'array' }],
    };
    const dicBusiness = busType;
    const pColumns = stepColumns;
    const currStep = ref(null);
    onMounted(async () => {
      //判断当前类型是否新增
    });
    const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
      labelWidth: 100,
      schemas: show1 ? accountFormSchema : accountFormSchema2,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 18,
      },
    });

    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      await resetFields();
      setModalProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      postData.value = data?.record ? data?.record : null;
      if (unref(isUpdate)) {
        rowId.value = data.record.id;
        setFieldsValue(data.record);
      }
    });

    const getTitle = computed(() =>
      !unref(isUpdate) ? (unref(postData) ? '查看流程配置' : '新增流程配置') : '编辑流程配置'
    );
    async function handleSubmit() {
      setModalProps({ confirmLoading: true });
      try {
        const { createMessage } = useMessage();
        closeModal();
        emit('success');
        createMessage.success(unref(isUpdate) ? '编辑成功' : '新增成功');
      } finally {
        setTimeout(() => {
          setModalProps({ confirmLoading: false });
        }, 300);
      }
    }

    function preProcessData(data) {
      Object.keys(data).forEach((item) => {
        if (typeof data[item] === 'undefined' || data[item] === null || data[item] === '') {
          delete data[item];
        }
      });
      return data;
    }

    function paramsToFormData(obj) {
      const data = preProcessData(obj);
      const formData = new FormData();
      Object.keys(data).forEach((key) => {
        if (data[key] instanceof Array) {
          data[key].forEach((item) => {
            formData.append(key, item);
          });
          return;
        }
        formData.append(key, obj[key]);
      });
      return formData;
    }

    /**
     * 编辑步骤
     */
    const editStep = (row) => {
      currStep.value = row;
    };

    const updateStep = (row) => {
      nextTick(() => {
        const obj = formState.steps.find((item) => item.xh === row.xh);
        if (obj) {
          formState.steps.forEach((item) => {
            if (item.xh === row.xh) {
              for (const key in row) {
                item[key] = row[key];
              }
            }
          });
        } else {
          formState.steps.push(row);
        }
      });
    };

    const reduceStep = (row) => {
      const obj = formState.steps.find((item) => item.xh === row.xh);
      const index = formState.steps.indexOf(obj as any);
      if (index > -1) formState.steps.splice(index, 1);
      //当前数据显示最后一个
      currStep.value = formState.steps[formState.steps.length - 1];
    };

    const onSubmit = () => {
      formRef.value
        .validate()
        .then(() => {
          console.log('values', formState, toRaw(formState));
        })
        .catch((error: ValidateErrorEntity<FormState>) => {
          console.log('error', error);
        });
    };
    const resetForm = () => {
      formRef.value.resetFields();
    };

    const customRow = (record, index) => {
      return {
        on: {
          // 鼠标单击行
          click: (event) => {
            debugger
            event.currentTarget.parentNode.querySelectorAll('tr').forEach((item) => {
              item.style.background = 'white';
            });
            event.currentTarget.style.background = 'green';
          },
        },
      };
    };

    return {
      postData,
      formRef,
      formState,
      rules,
      dicBusiness,
      pColumns,
      currStep,
      customRow,
      registerModal,
      registerForm,
      handleSubmit,
      getTitle,
      show1,
      onSubmit,
      resetForm,
      editStep,
      updateStep,
      reduceStep,
    };
  },
});
</script>
<style scoped lang="less">
.process-cofig {
  position: absolute;
  height: calc(100% - 14px);
  width: calc(100% - 30px);
  padding: 0 20px;

  .info-item {
    width: 100%;
    margin-bottom: 20px;
    .title {
      padding-left: 10px;
      border-left: 3px solid #2d74e7;
      height: 16px;
      line-height: 16px;
      font-family: Source Han Sans CN;
      font-size: 16px;
      font-weight: 300;
      letter-spacing: 0px;
      color: #333333;
    }
    .form-continer {
      padding-top: 20px;
      height: calc(100% - 36px);
      .left-continer {
        float: left;
        height: 100%;
        width: 440px;
        padding: 20px;
        background: #ffffff;
        box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.1), inset 0px 2px 2px 0px rgba(0, 0, 0, 0.05);
      }
      .right-continer {
        float: right;
        padding: 20px;
        height: 100%;
        width: calc(100% - 440px);
        background: #ffffff;
        box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.1), inset 0px 2px 2px 0px rgba(0, 0, 0, 0.05);
      }
    }
  }
  .info-item-basic {
    height: 68px;
  }
  .info-item-steps {
    height: calc(100% - 88px);
  }
}
</style>
