<template>
  <div class="plan-change sop-step">
    <t-collapse class="sop-step-mid" defaultExpandAll>
      <t-collapse-panel disabled>
        <template #expandIcon></template>
        <template #header>
          项目派单信息(SOP流水单号：{{ sopInfo.sopNo }})
        </template>
        <t-form colon label-width="72px">
          <t-row :gutter="[0, 4]">
            <t-col :span="3">
              <t-form-item label="项目单号">{{ sopInfo.crmNo }}</t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="项目名称">{{ sopInfo.crmName }}</t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="派单时间">{{
                timestampFilter(sopInfo.beginTime)
              }}</t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="客户经理">{{
                sopInfo.customManagerName
              }}</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="考试开始时间" label-width="100px">{{
                timestampFilter(sopInfo.examStartTime)
              }}</t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="考试结束时间" label-width="100px">{{
                timestampFilter(sopInfo.examEndTime)
              }}</t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="实施产品">{{
                sopInfo.productName
              }}</t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="服务单元">{{
                sopInfo.serviceName
              }}</t-form-item>
            </t-col>
          </t-row>
        </t-form>
      </t-collapse-panel>
    </t-collapse>
    <t-collapse class="sop-step-mid" defaultExpandAll>
      <t-collapse-panel disabled>
        <template #expandIcon></template>
        <template #header> SOP项目计划变更说明 </template>
        <p class="red">
          SOP项目计划需要变更时，可手动发起一个或多个申请，质控专员审核后，在SOP流程中进行计划变更调整，完成变更后，申请流程结束并通知到发起申请人。
        </p>
      </t-collapse-panel>
    </t-collapse>

    <div class="sop-step-list" style="flex-direction: column">
      <t-form
        class="sop-step-body"
        ref="formRef"
        :data="formData"
        :rules="rules"
        labelAlign="top"
        colon
      >
        <t-row :gutter="[0, 20]">
          <template v-if="!IS_NEW_MODE">
            <t-col :span="4">
              <t-form-item label="报备申请人">
                {{ sopInfo.createRealName }}
              </t-form-item>
            </t-col>
            <t-col :span="4" :offset="1">
              <t-form-item label="报备申请时间">
                {{ timestampFilter(sopInfo.createTime || sopInfo.flowTime) }}
              </t-form-item>
            </t-col>
          </template>
          <t-col :span="12">
            <t-form-item label="变更类型" requiredMark>
              <div style="padding-top: 3px">
                <t-radio-group v-model="formData.type" :disabled="readonly">
                  <t-radio
                    :value="item.value"
                    :key="item.value"
                    v-for="item in dictToOptionList(PLAN_CHANGE_TYPE)"
                    >{{ item.label }}</t-radio
                  >
                </t-radio-group>
                <div class="sub-title gray">
                  <p>
                    1.关键信息及计划变更：项目关键信息里填写的项目关键信息或时间计划内容调整；
                  </p>
                  <p> 2.项目取消：若项目取消，则只需填写变更原因后提交。 </p>
                </div>
              </div>
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item label="变更原因" name="reason">
              <t-input
                :disabled="readonly"
                v-model="formData.reason"
                placeholder="50字以内"
                :maxlength="50"
              ></t-input>
            </t-form-item>
          </t-col>
          <t-col :span="12" v-if="formData.type !== 'CANCEL'">
            <t-form-item
              label="项目信息及计划变更明细"
              name="contentJson"
              requiredMark
            >
              <dynamic-table
                ref="dTable"
                v-model="formData.contentJson"
                :columns="columns"
                :readonly="readonly"
              ></dynamic-table>
            </t-form-item>
          </t-col>
          <template v-if="!IS_NEW_MODE">
            <t-col :span="12">
              <div class="form-group-title"> 变更处理结果 </div>
            </t-col>
            <t-col :span="12">
              <t-form-item label="处理结果">
                <t-radio-group
                  v-model="formData.projectExchangeApprove"
                  :disabled="IS_VIEW_MODE"
                >
                  <t-radio value="FINISH">已完成</t-radio>
                  <t-radio value="NOT_UPDATE"
                    >经沟通，取消变更(原因请填写变更备注)</t-radio
                  >
                  <t-radio value="PARTIAL_UPDATE"
                    >经沟通，部分变更（详情请填写变更备注）</t-radio
                  >
                </t-radio-group>
              </t-form-item>
            </t-col>
            <t-col :span="12">
              <t-form-item label="" name="remark">
                <div style="width: 100%">
                  <p style="font-size: 14px; color: #595959; margin-bottom: 6px"
                    >变更备注：<span class="red"
                      >(取消变更、部分变更，此项必填)</span
                    ></p
                  >
                  <t-textarea
                    v-model="formData.remark"
                    :disabled="IS_VIEW_MODE"
                  ></t-textarea>
                </div>
              </t-form-item>
            </t-col>
          </template>
        </t-row>
      </t-form>
      <t-space
        v-if="IS_VIEW_MODE"
        class="sop-step-footer"
        style="flex-direction: row"
      >
        <t-button theme="primary" @click="cancelHandle">返回</t-button>
      </t-space>
      <t-space v-else class="sop-step-footer">
        <t-button theme="primary" @click="submitHandle">提交</t-button>
        <t-button theme="default" @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>
    </div>
  </div>
</template>
<script setup name="PlanChange">
import { ref, computed, reactive } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import {
  ChevronLeftDoubleIcon,
  ChevronRightDoubleIcon,
} from 'tdesign-icons-vue-next';
import dynamicTable from '@/components/common/dynamic-table/index.vue';
import { dictToOptionList } from '@/utils/tool';
import { PLAN_CHANGE_TYPE } from '@/config/constants';
import {
  createPlanChange,
  approvePlanChange,
  planChangeDetail,
} from '@/api/sop';
import { omit } from 'lodash';
import { timestampFilter } from '@/utils/filter';
import { timeNumberToText } from '@/utils/tool';

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

const sopInfo = ref({ ...props.sop });
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 IS_NEW_MODE = computed(() => {
  return props.type === 'new';
});
const IS_VIEW_MODE = computed(() => {
  return props.type === 'view';
});
const readonly = computed(() => {
  return !IS_NEW_MODE.value;
});

const columns = computed(() => [
  {
    colKey: 'before',
    title: '变更字段（全称）',
    comp: {
      type: 'text',
      attrs: {
        clearable: true,
      },
    },
    rules: [
      { required: true, message: '不能为空', type: 'error', trigger: 'change' },
    ],
  },
  {
    colKey: 'after',
    title: '变更后内容',
    comp: {
      type: 'text',
      attrs: {
        clearable: true,
      },
    },
    rules: [
      {
        required: true,
        message: '不能为空',
        type: 'error',
        trigger: 'change',
      },
    ],
  },
  {
    colKey: 'remark',
    title: '备注',
    comp: {
      type: 'text',
      attrs: {
        clearable: true,
      },
    },
  },
]);

const formRef = ref(null);
let formData = reactive({
  serviceId: '',
  sopNo: '',
  crmNo: '',
  type: 'PLAN',
  flowDeploymentId: '',
  reason: '',
  contentJson: [],
  projectExchangeApprove: 'FINISH',
  remark: '',
});

const initData = async () => {
  if (IS_NEW_MODE.value) {
    formData.serviceId = props.sop.serviceId;
    formData.sopNo = props.sop.sopNo;
    formData.crmNo = props.sop.crmNo;
    formData.flowDeploymentId = props.sop.flowDeploymentId;
    return;
  }

  // audit
  const res = await planChangeDetail(props.sop.id || props.sop.objId);
  sopInfo.value.beginTime = res.crmInfo.crmBeginTime;
  sopInfo.value.customManagerName = res.crmInfo.customManagerName;
  sopInfo.value.customManagerTypeStr = props.sop.customTypeStr;
  sopInfo.value.examStartTime = res.crmInfo.examStartTime;
  sopInfo.value.examEndTime = res.crmInfo.examEndTime;
  sopInfo.value.productName = res.crmInfo.productName;
  sopInfo.value.statusStr = props.sop.projectExchangeFlowStatusStr;

  flowApproveHistoryList.value = getFlowApproveHistoryList(
    res.flowApproveHistoryList
  );

  for (const key in res.tbProjectExchange) {
    if (Object.hasOwnProperty.call(formData, key)) {
      formData[key] = res.tbProjectExchange[key];
    }
  }
  formData.contentJson = JSON.parse(formData.contentJson);
};
initData();

const rules = computed(() => {
  return {
    reason: [
      {
        required: true,
        message: '请填写变更原因',
        type: 'error',
        trigger: 'change',
      },
    ],
    contentJson: [
      {
        validator: (val) => {
          if ((!val || !val.length) && formData.type !== 'CANCEL')
            return { result: false, message: '请至少填写一行数据' };

          return { result: true, type: 'success' };
        },
      },
    ],
    remark: [
      {
        validator: (val) => {
          if (!val && formData.projectExchangeApprove !== 'FINISH') {
            return {
              result: false,
              message: '请填写备注',
            };
          }
          return {
            result: true,
            type: 'success',
          };
        },
      },
    ],
  };
});

const toViewHistory = () => {
  stepHistoryShow.value = !stepHistoryShow.value;
};

const submitHandle = async () => {
  const valid = await formRef.value.validate();
  if (valid !== true) return MessagePlugin.error('请完善必填项');

  if (IS_NEW_MODE.value) {
    const res = await createPlanChange({
      ...omit(formData, ['projectExchangeApprove', 'remark']),
      contentJson: JSON.stringify(formData.contentJson),
      flowApprove: 'START',
    }).catch(() => {});
    if (!res) return;
  } else {
    // 流程审批
    const res = await approvePlanChange({
      flowApprove: 'PASS',
      projectExchangeApprove: formData.projectExchangeApprove,
      remark: formData.remark,
      taskId: props.sop.taskId,
    }).catch(() => {});
    if (!res) return;
  }

  MessagePlugin.success('提交成功');
  emit('confirm');
};

const cancelHandle = () => {
  emit('cancel');
};
</script>
