<template>
  <div class="quality-issue sop-step">
    <t-collapse class="sop-step-mid" defaultExpandAll>
      <t-collapse-panel disabled>
        <template #expandIcon></template>
        <template #header> SOP信息 </template>
        <t-form colon label-width="85px">
          <t-row :gutter="[0, 4]">
            <t-col :span="3">
              <t-form-item label="服务单元">{{
                sopInfo.serviceName
              }}</t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="SOP流水号">{{ sopInfo.sopNo }}</t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="客户类型">{{
                sopInfo.customManagerTypeStr
              }}</t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="客户名称">{{
                sopInfo.customName
              }}</t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="项目单号">{{ sopInfo.crmNo }}</t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="实施产品">{{
                sopInfo.productName
              }}</t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="项目名称">{{ sopInfo.crmName }}</t-form-item>
            </t-col>
          </t-row>
        </t-form>
      </t-collapse-panel>
    </t-collapse>

    <t-tabs
      class="sop-step-list"
      v-model="curStep"
      placement="left"
      @change="stepChange"
    >
      <t-tab-panel
        v-for="item in tabs"
        :key="item.taskKey"
        :value="item.value"
        :label="item.label"
      >
        <t-form
          ref="form"
          class="sop-step-body"
          colon
          :label-width="labelWidth"
          :rules="rules"
          :data="formData"
          labelAlign="top"
        >
          <t-row :gutter="[0, 20]">
            <t-col
              :span="
                fullWidthCodes.includes(config.code)
                  ? 12
                  : config.span < 6
                  ? 6
                  : config.span || 6
              "
              v-for="config in curFormConfig"
              :key="config.id"
            >
              <dynamic-form-item
                v-if="config.visable"
                :config="config"
                :labelWidth="labelWidth"
                @change="itemValueChange"
              ></dynamic-form-item>
            </t-col>
          </t-row>
        </t-form>
        <t-space class="sop-step-footer">
          <template v-if="showAction">
            <t-button theme="primary" @click="submitHandle('START')"
              >提交</t-button
            >
            <t-button theme="default" @click="cancelHandle">取消</t-button>
          </template>
        </t-space>
      </t-tab-panel>
    </t-tabs>
  </div>
</template>

<script setup name="QualityIssue">
import { ref, computed, watch, reactive } from 'vue';
import {
  issuesFeedbackSaveApi,
  issuesFeedbackApproveApi,
} from '@/api/project-quality';
import { flowFormPropertiesApi, sopFlowViewApi } from '@/api/sop';
import { MessagePlugin } from 'tdesign-vue-next';
import DynamicFormItem from '../../components/dynamic-form-item/index.vue';
import { CUSTOMER_TYPE } from '@/config/constants';

const props = defineProps({
  sop: {
    type: Object,
    default() {
      return {};
    },
  },
  type: {
    type: String,
    default: 'new',
  },
});
const emit = defineEmits(['confirm', 'cancel']);

const IS_NEW_MODE = computed(() => {
  return props.type === 'new';
});
const IS_FILL_MODE = computed(() => {
  return props.type === 'fill';
});

const sopInfo = reactive({
  serviceName: props.sop.serviceName,
  sopNo: props.sop.sopNo,
  customManagerTypeStr: props.sop.customManagerTypeStr,
  customName: props.sop.customName,
  crmNo: props.sop.crmNo,
  productName: props.sop.productName,
  crmName: props.sop.crmName,
});

const needValueCodes = [
  'NUMBER', //新增
  'TEXT',
  'DATE',
  'SINGLE_SELECT',
  'MULTIPLE_SELECT',
  'CHECKBOX',
  'TEXTAREA',
  'TABLE',
  'RADIO',
  'RADIO_WITH_INPUT',
  'SIGN',
  'DEVICE_OUT_TABLE',
  'DEVICE_IN_TABLE',
  'FILE',
];
const rules = ref({});
const formData = ref({});

const loading = ref(false);
const labelWidth = ref(120);
const fullWidthCodes = ref([
  'TABLE',
  'FORM_GROUP_TITLE',
  'TEXTAREA',
  'ONLY_TITLE',
  'DEVICE_OUT_TABLE',
  'DEVICE_IN_TABLE',
]);
const form = ref(null);
const allSteps = ref([]);
const tabs = ref([]);
const curStep = ref('');
const currFlowTaskResultSetup = ref(null);
const curStepSetup = ref(1);
const flowId = props.sop.flowId;
const crmInfo = ref({});

const initNew = async () => {
  loading.value = true;
  const res = await flowFormPropertiesApi({
    flowDeploymentId: props.sop.flowDeploymentId,
  });
  loading.value = false;

  allSteps.value = [res.formProperties];
  tabs.value = allSteps.value.map((item) => {
    return {
      value: item.taskName,
      label: item.taskName,
    };
  });
  curStep.value = tabs.value.slice(-1)[0].value;
};
const initFill = async () => {
  loading.value = true;
  const res = await sopFlowViewApi({ flowId });
  crmInfo.value = res.crmInfo;
  sopInfo.crmName = crmInfo.value.crmName;
  sopInfo.productName = crmInfo.value.productName;
  sopInfo.serviceName = crmInfo.value.serviceUnitName;
  sopInfo.sopNo = res.sopNo;
  sopInfo.customManagerTypeStr = CUSTOMER_TYPE[crmInfo.value.customType];

  curStep.value = res.currFlowTaskResult.taskName;
  currFlowTaskResultSetup.value = res.currFlowTaskResult.setup;
  curStepSetup.value = res.currFlowTaskResult.setup;
  res.flowTaskHistoryList = res.flowTaskHistoryList || [];
  res.flowTaskHistoryList.forEach((item) => {
    item.formProperty.forEach((v) => {
      v.writable = false;
    });
  });
  allSteps.value = [...res.flowTaskHistoryList, res.currFlowTaskResult];
  tabs.value = [
    ...res.flowTaskHistoryList.map((item) => {
      return {
        value: item.taskName,
        label: item.taskName,
      };
    }),
    {
      value: res.currFlowTaskResult.taskName,
      label: res.currFlowTaskResult.taskName,
    },
  ];
  allSteps.value.forEach((item) => {
    item.formProperty.forEach((prop) => {
      prop.value = prop.value ? JSON.parse(prop.value).value : null;
    });
  });
  loading.value = false;
};

const init = () => {
  if (IS_NEW_MODE.value) {
    // 发起流程
    initNew();
  } else {
    initFill();
  }
};
init();

const showAction = computed(() => {
  if (IS_NEW_MODE.value) return true;

  if (
    IS_FILL_MODE.value &&
    curStepSetup.value === currFlowTaskResultSetup.value
  )
    return true;

  return false;
});

const curFormConfig = computed(() => {
  const stepData = allSteps.value.find(
    (item) => item.taskName === curStep.value
  );
  if (!stepData) return [];

  const formProperty = stepData.formProperty || [];
  return formProperty;
});
watch(curFormConfig, (val) => {
  formData.value = val.reduce((obj, item) => {
    if (needValueCodes.includes(item.code)) {
      obj[item.formName] = item.value || null;
    }
    return obj;
  }, {});
  rules.value = val.reduce((obj, item) => {
    let ruleItem =
      item.required && needValueCodes.includes(item.code)
        ? {
            required: true,
            message: `${item.title}不能为空`,
            type: 'error',
            trigger: 'change',
          }
        : null;
    if (ruleItem) {
      obj[item.formName] = [ruleItem];
    }
    return obj;
  }, {});
});

const stepChange = () => {
  const curStepData = allSteps.value.find(
    (item) => item.taskName === curStep.value
  );
  curStepSetup.value = curStepData.setup;
};

const itemValueChange = ({ prop, value }) => {
  console.log(prop, ':', value);
  formData.value[prop] = value;
};

const getFormData = () => {
  let data = {};
  const curStepData = allSteps.value.find(
    (item) => item.taskName === curStep.value
  );
  data = { ...curStepData };
  data.formProperty = data.formProperty.map((item) => {
    return {
      ...item,
      value: JSON.stringify({ value: formData.value[item.formName] || null }),
    };
  });

  return JSON.stringify(data);
};

// 填报-提交
const submitHandle = async (flowApprove = 'START') => {
  if (flowApprove === 'START') {
    const valid = await form.value[0].validate();
    if (valid !== true) return;

    flowApprove = curStepSetup.value === 1 ? 'START' : 'PASS';
  }

  if (IS_FILL_MODE.value) {
    const res = await issuesFeedbackApproveApi({
      taskId: props.sop.taskId,
      formProperties: getFormData(),
      approve: flowApprove,
    }).catch(() => {});
    if (!res) return;
  } else if (IS_NEW_MODE.value) {
    const res = await issuesFeedbackSaveApi({
      serviceId: props.sop.serviceId,
      crmNo: props.sop.crmNo,
      flowDeploymentId: props.sop.flowDeploymentId,
      sopNo: props.sop.sopNo,
      formProperties: getFormData(),
      flowApprove,
    }).catch(() => {});
    if (!res) return;
  }

  MessagePlugin.success('保存成功');
  emit('confirm');
};
const cancelHandle = () => {
  emit('cancel');
};
</script>
