<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-col
              :span="11"
              v-if="
                curStepData.taskKey == 'f_usertask_quality_problem_check_3' ||
                curStepData.taskKey ==
                  'f_usertask_quality_problem_third_check_4'
              "
            >
              <div class="form-group-title m-l-15px m-b-10px">{{
                `历史${
                  curStepData.taskKey == 'f_usertask_quality_problem_check_3'
                    ? '甲'
                    : '乙'
                }方复核意见：`
              }}</div>
              <div class="history-box m-l-15px">
                <div
                  v-for="(item, index) in flowFormSuggestionResultList"
                  :key="index"
                  class="history-item flex items-center"
                >
                  <div class="left-info">
                    <div class="left-head flex justify-between items-center">
                      <div class="flex items-center h-full">
                        <span class="u-name">{{ item.approveUserName }}</span>
                        <t-tag
                          v-if="item.approveOperation == '同意'"
                          theme="success"
                          variant="light"
                          >同意</t-tag
                        >
                        <t-tag v-else theme="danger" variant="light"
                          >不同意</t-tag
                        >
                      </div>
                      <div class="time">{{
                        dateFormat(item.createTime, 'yyyy-MM-dd HH:mm')
                      }}</div>
                    </div>
                    <div class="left-body">
                      <div class="label">初审意见：</div>
                      <div class="content">
                        {{ item.approveFormSuggestion }}
                      </div>
                    </div>
                  </div>
                  <div class="img-box">
                    <div class="img-wrap">
                      <image-view
                        :width="46"
                        :height="46"
                        :images="[item.approveFormSign]"
                      ></image-view>
                    </div>
                  </div>
                </div>
              </div>
            </t-col>
          </t-row>
        </t-form>
        <t-space v-if="showAction" class="sop-step-footer">
          <t-button theme="primary" @click="submitHandle('START')"
            >提交</t-button
          >
          <t-button theme="default" @click="cancelHandle">取消</t-button>
        </t-space>
        <t-space v-else class="sop-step-footer" style="flex-direction: row">
          <t-button theme="primary" @click="cancelHandle">返回</t-button>
        </t-space>
        <!-- setup history -->
        <div v-if="flowApproveHistoryList.length" class="sop-step-history">
          <div class="sop-step-history-label" @click="toViewHistory">
            <ChevronRightDoubleIcon v-if="stepHistoryShow" />
            <ChevronLeftDoubleIcon v-else />
            流程动态
          </div>
          <transition name="fade-slide" mode="out-in" appear>
            <div v-if="stepHistoryShow" class="sop-step-history-content">
              <div class="content-head">
                <h2>
                  {{ sopInfo.statusStr }}
                </h2>
              </div>
              <div class="content-body">
                <t-collapse>
                  <t-collapse-panel
                    v-for="(item, findex) in flowApproveHistoryList"
                    :key="findex"
                    :header="item.taskName"
                  >
                    <template #headerRightContent>
                      <t-space size="small">
                        <span class="collapse-head-right">{{
                          timestampFilter(item.createTime)
                        }}</span>
                        <t-tag
                          :theme="
                            item.approveOperation === 'REJECT'
                              ? 'danger'
                              : 'success'
                          "
                          variant="light"
                        >
                          {{ item.approveRemark }}
                        </t-tag>
                      </t-space>
                    </template>
                    <div class="content-detail">
                      <div class="content-detail-head">
                        {{ item.approveUserName || '--' }}
                      </div>
                      <div class="content-detail-body">
                        <p>开始处理：{{ timestampFilter(item.createTime) }}</p>
                        <p>处理耗时：{{ item.duration }}</p>
                      </div>
                    </div>
                  </t-collapse-panel>
                </t-collapse>
              </div>
            </div>
          </transition>
        </div>
      </t-tab-panel>
    </t-tabs>
  </div>
</template>

<script setup name="QualityIssue">
import { ref, computed, watch, reactive } from 'vue';
import {
  ChevronLeftDoubleIcon,
  ChevronRightDoubleIcon,
} from 'tdesign-icons-vue-next';
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';
import { timeNumberToText, dateFormat } from '@/utils/tool';
import { timestampFilter } from '@/utils/filter';
const props = defineProps({
  sop: {
    type: Object,
    default() {
      return {};
    },
  },
  type: {
    type: String,
    default: 'new',
  },
});
const emit = defineEmits(['confirm', 'cancel']);

const stepHistoryShow = ref(false);
const flowApproveHistoryList = ref([]);
function getFlowApproveHistoryList(data) {
  if (!data) return [];

  let lastTime = 0;
  // return data.map((item, index) => {
  //   let nitem = { ...item };
  //   nitem.duration =
  //     index === 0 ? '-' : timeNumberToText(item.createTime - lastTime);
  //   lastTime = item.createTime;
  //   return nitem;
  // });
  for (let i = data.length - 1; i >= 0; i--) {
    let item = data[i];
    item.duration =
      i === data.length - 1
        ? '-'
        : timeNumberToText(item.createTime - lastTime);
    lastTime = item.createTime;
  }
  return data;
}
const toViewHistory = () => {
  stepHistoryShow.value = !stepHistoryShow.value;
};

const IS_NEW_MODE = computed(() => {
  return props.type === 'new';
});
const IS_VIEW_MODE = computed(() => {
  return props.type === 'view';
});
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,
  statusStr: props.sop.statusStr,
});
const flowFormSuggestionJiaResultList = ref([]);
const flowFormSuggestionYiResultList = ref([]);
const flowFormSuggestionResultList = computed(() => {
  return curStepData.value.taskKey == 'f_usertask_quality_problem_check_3'
    ? flowFormSuggestionJiaResultList.value
    : flowFormSuggestionYiResultList.value;
});
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 approveRejectFormIds = {
  f_usertask_quality_problem_check_3: ['approve_radio_3'],
  f_usertask_quality_problem_third_check_4: ['approve_radio_4'],
};

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];
  flowFormSuggestionJiaResultList.value =
    res.flowFormSuggestionJiaResultList || [];
  flowFormSuggestionYiResultList.value =
    res.flowFormSuggestionYiResultList || [];

  res.flowTaskHistoryList = res.flowTaskHistoryList || [];
  res.flowTaskHistoryList.forEach((item) => {
    item.formProperty.forEach((v) => {
      v.writable = false;
    });
  });
  tabs.value = [
    ...res.flowTaskHistoryList.map((item) => {
      return {
        value: item.taskName,
        label: item.taskName,
      };
    }),
  ];

  if (res.currFlowTaskResult) {
    curStep.value = res.currFlowTaskResult.taskName;
    currFlowTaskResultSetup.value = res.currFlowTaskResult.setup;
    curStepSetup.value = res.currFlowTaskResult.setup;

    allSteps.value = [...res.flowTaskHistoryList, res.currFlowTaskResult];
    tabs.value.push({
      value: res.currFlowTaskResult.taskName,
      label: res.currFlowTaskResult.taskName,
    });
  } else {
    allSteps.value = [...res.flowTaskHistoryList];
    curStepSetup.value = allSteps.value[0].setup;
    curStep.value = allSteps.value[0].taskName;
  }

  allSteps.value.forEach((item) => {
    item.formProperty.forEach((prop) => {
      prop.value = prop.value ? JSON.parse(prop.value).value : null;
    });
  });
  flowApproveHistoryList.value = getFlowApproveHistoryList(
    res.flowApproveHistoryList
  );
  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 || [];
  if (IS_VIEW_MODE.value) {
    formProperty.forEach((item) => {
      item.writable = false;
    });
  }
  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') => {
  const curStepData = allSteps.value.find(
    (item) => item.taskName === curStep.value
  );
  if (flowApprove === 'START') {
    const valid = await form.value[0].validate();
    if (valid !== true) return MessagePlugin.error('请完善必填项');

    if (curStepSetup.value !== 1) {
      const rejectFormIds = approveRejectFormIds[curStepData.taskKey];
      if (
        rejectFormIds &&
        rejectFormIds.some((fid) => formData.value[fid] === '0')
      ) {
        flowApprove = 'REJECT';
      } else {
        flowApprove = 'PASS';
      }
    }
  }

  if (IS_FILL_MODE.value) {
    let data = {
      taskId: props.sop.taskId,
      formProperties: getFormData(),
      approve: flowApprove,
    };
    if (flowApprove === 'REJECT') {
      // 目前只打回给定的允许打回的第一个选项
      data.setup = curStepData.approveRejectList[0].setup;
    }
    const res = await issuesFeedbackApproveApi(data).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');
};
const curStepData = computed(
  () => allSteps.value.find((item) => item.taskName === curStep.value) || {}
);
</script>
<style lang="less" scoped>
.history-box {
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  padding: 4px 15px;
  .history-item {
    width: 100%;
    padding: 8px 0;
    &:not(:last-child) {
      border-bottom: 1px solid #e5e5e5;
    }
    .left-info {
      width: calc(100% - 75px);
      .left-head {
        height: 26px;
        .u-name {
          font-size: 14px;
          color: #262626;
          font-weight: 500;
          margin-right: 12px;
        }
        .time {
          color: #8c8c8c;
        }
      }
      .left-body {
        padding: 6px 0;
        display: flex;
        .label {
          color: #595959;
          width: 70px;
        }
        .content {
          width: calc(100% - 70px);
          color: #262626;
        }
      }
    }
    .img-box {
      padding: 5px 0 5px 20px;
      .img-wrap {
        width: 52px;
        height: 52px;
        border-radius: 4px;
        border: 1px solid #e5e5e5;
        background-color: #f0f0f0;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
</style>
