<template>
  <div>
    <el-dialog
      title="审批"
      :visible.sync="checkDialog"
      width="90%"
      @close="close"
    >
      <div class="check-dialog">
        <div :class="leftHide ? '' : 'left-step'">
          <i
            :class="leftHide ? 'el-icon-caret-right' : 'el-icon-caret-left'"
            size="32"
            class="collapse"
            @click="leftClick"
          />
          <el-steps
            v-show="!leftHide"
            direction="vertical"
            :active="processList.length"
            class="step-list"
          >
            <el-step
              v-for="(item, index) in processList"
              :key="index"
            >
              <div slot="title">
                <p
                  v-if="item.action"
                  style="color: #333"
                >
                  {{ item.EndTime
                  }}<span style="margin-left: 20px">{{ item.action }}</span>
                </p>
                <p
                  v-else
                  style="text-align: center; color: #333"
                >处理中</p>
                <div :class="item.action ? 'step-content' : 'step-handle'">
                  {{ item.content }}
                </div>
              </div>
            </el-step>
          </el-steps>
        </div>
        <div :class="leftHide ? 'right-auto' : 'right-table'">
          <PublicTable
            v-if="!routeType"
            ref="table"
            class="table"
            row-key="formName"
            :loading="loading"
            :has-index="false"
            :has-operation="false"
            :table-data="table.data"
            :table-column="table.columns"
            :operation-fixed="false"
            :is-need-pagination="false"
            :is-need-customcolumn="false"
          />
          <div v-else>交易审批</div>
        </div>
      </div>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <flip-countdown
          v-if="showCountdown"
          :key="countdownKey"
          :deadline="deadline"
          :show-days="false"
          :show-hours="false"
          :labels="{}"
          :countdown-size="'20px'"
          style="float:left;width:auto"
          @timeElapsed="close"
        />
        <el-button
          type="primary"
          :size="$buttonSize"
          @click="handleViewProcess"
        >查看流程</el-button>
        <el-button
          v-for="item in operationList"
          :key="item.id"
          type="primary"
          :size="$buttonSize"
          @click="invokeMethod(item.codeName)"
        >{{ item.codeLocalName }}</el-button>
      </div>
    </el-dialog>
    <ProcessDialog
      :show-process.sync="showProcess"
      :select-row="selectRow"
    />
    <el-dialog
      :title="dialogTitle"
      :visible.sync="backDialog"
      width="60%"
      :modal-append-to-body="false"
    >
      <publicForm
        ref="publicForm"
        :form-arr="formArr"
        :form-data="formData"
        @outOperation="outOperation"
      />
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          :size="$buttonSize"
          @click="save"
        >保存</el-button>
        <el-button
          type="primary"
          :size="$buttonSize"
          @click="dialogClose"
        >取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ProcessDialog from './processDialog.vue';
import PublicTable from '@/components/table/index.vue';
import publicForm from '@/components/form/index.vue';
import FlipCountdown from 'vue2-flip-countdown';
import moment from 'moment';
import { dateFormat } from '../../../../utils';

export default {
  components: {
    ProcessDialog,
    PublicTable,
    publicForm,
    FlipCountdown,
  },
  props: {
    isShow: {
      type: Boolean,
      default: false,
    },
    selectRow: {
      type: Object,
      default: () => {},
    },
    activeIndex: {
      type: [String, Number],
      default: null,
    },
  },
  data() {
    return {
      countDownKey: 0,
      // deadline: moment()
      //   .add(5, 'm')
      //   .format('YYYY-MM-DD HH:mm:ss'),
      deadline: null,
      showCountdown: false,
      dialogTitle: '',
      backDialog: false,
      leftHide: false,
      checkDialog: false,
      showProcess: false,
      processList: [],
      operationList: [],
      table: {
        data: [],
        columns: [
          {
            prop: 'formName',
            minWidth: '100px',
            align: 'center',
            // label: this.$t('field.formName'),
            label: '变更要素',
          },
          {
            prop: 'before',
            minWidth: '100px',
            align: 'center',
            // label: this.$t('field.after'),
            label: '审核前',
          },
          {
            prop: 'after',
            minWidth: '100px',
            align: 'center',
            // label: this.$t('field.before'),
            label: '审核后',
          },
        ],
      },
      formArr: [
        {
          type: 'select',
          prop: 'opType',
          span: 24,
          attrs: {
            label: '常用语:',
          },
          options: [],
          rules: { required: true, message: '请选择' },
        },
        {
          type: 'textarea',
          prop: 'msg',
          span: 24,
          attrs: {
            label: '审批回复:',
            placeholder: '请填写',
            minRows: 3,
            // maxRows: 2,
          },
        },
      ],
      // 默认值
      formData: {
        opType: '',
        msg: '',
      },
    };
  },
  computed: {
    routeType() { // 是否是交易审批 参数审批
      return this.$route.meta.extraData.extraParams.type === 'dcs/dcs';
    },
  },
  watch: {
    isShow: {
      handler(nv) {
        this.$nextTick(async() => {
          if (nv) {
            await this.init();
          }
        });
      },
    },
  },
  mounted() {},
  methods: {
    outOperation(val, index, prop, num) {
      console.log(val, index, prop, num, 'lklkl');
      if (val) {
        if (prop === 'opType') {
          this.formData.msg = this.formArr[0].options.filter(
            (v) => v.value == val,
          )[0].label;
        }
      }
    },
    leftClick() {
      this.leftHide = !this.leftHide;
    },
    async init() {
      await this.getUserFlowOperationList();
      this.getFlowLog();
      this.getFlowCompareList();
    },
    invokeMethod(methodName) {
      if (typeof this[methodName] === 'function') {
        this[methodName]();
      } else {
        console.warn(`方法 ${methodName} 不存在`);
      }
    },
    close() {
      this.checkDialog = false;
      this.table.data = [];
      this.$emit('update:isShow', false);
      this.showCountdown = false;
    },
    handleViewProcess() {
      // 查看流程
      console.log('查看流程', this.selectRow);
      this.showProcess = true;
    },
    Agree() {
      // 同意
      this.dialogTitle = '同意';
      this.getBackTypeList();
    },
    Back() {
      // 退回发起
      this.dialogTitle = '退回发起';
      this.getBackTypeList();
    },
    getBackTypeList() {
      this.backDialog = true;
      this.$apis.getBackList({ codifierGrpCodes: 'QuickReply' }).then((res) => {
        this.formArr[0].options = res.data.result.QuickReply;
      });
    },
    async save() {
      if (this.$refs.publicForm.submitForm()) {
        console.log(this.formData, 'success');
        const temp = await this.$confirmAction(
          '确认提交该笔审批吗?',
          'warning',
          '审批',
        );
        if (temp) {
          this.$apis
            .backSubmit({ ...this.selectRow, ...this.formData })
            .then((res) => {
              this.$message.success(res.message);
              this.$parent.getTopSta();
            });
        }
      } else {
        console.log('error');
      }
    },
    dialogClose() {
      this.backDialog = false;
      this.$refs.publicForm.resetForm();
    },
    Reject() {
      // 退回上一步
      this.dialogTitle = '退回上一步';
      this.getBackTypeList();
    },
    NoPass() {
      // 拒绝
      this.dialogTitle = '拒绝';
      this.getBackTypeList();
    },
    CancelRequest() {
      // 取消申请
      this.dialogTitle = '取消申请';
      this.getBackTypeList();
    },
    StartModified() {
      // 发起修改
      this.dialogTitle = '发起修改';
      this.getBackTypeList();
    },
    Pass() { // 直接通过
      this.dialogTitle = '直接通过';
      this.getBackTypeList();
    },
    initCountdown() {
      this.showCountdown = false;
      this.deadline = moment().add(5, 'm').add(1, 's').format('YYYY-MM-DD HH:mm:ss');
      this.$nextTick(() => {
        this.showCountdown = true;
      });
    },
    async getUserFlowOperationList() {
      // 获取流程操作按钮
      const { taskId, dealNo } = this.selectRow;
      const obj = { 1: 'WAITING', 2: 'FINISH', 3: 'REFUSE', 4: 'MINE' };
      await this.$apis
        .getUserFlowOperations({
          queryParam: {
            taskId,
            dealNo,
            type: obj[this.activeIndex],
            isLogPage: false,
          },
        })
        .then((res) => {
          this.operationList = res.data.result;
          // to-do 后续根据条件判断是否展示倒计时
          this.initCountdown();
          setTimeout(() => { // 延迟展示倒计时
            this.checkDialog = true;
          }, 1000);
          if (res.data.result.length === 0) {
            this.operationList = [
              {
                codeLocalName: '同意',
                codeName: 'Agree',
              },
              {
                codeLocalName: '退回发起',
                codeName: 'Back',
              },
              {
                codeLocalName: '退回上一步',
                codeName: 'Reject',
              },
              {
                codeLocalName: '拒绝',
                codeName: 'NoPass',
              },
            ];
          }
        });
    },
    getFlowLog() {
      this.$apis
        .getFlowLogBySerialNoRepeat({
          actNo: this.selectRow.dealNo,
        })
        .then((res) => {
          this.processList = res.data.result.datals.map((v) => {
            return {
              ...v,
              content:
                v.AssigneeId instanceof Array
                  ? v.AssigneeId.join(',')
                  : v.AssigneeId,
              EndTime: v.EndTime ? dateFormat('YYYY-MM-DD HH:mm:ss', new Date(v.EndTime)) : '',
            };
          });
        });
    },
    getFlowCompareList() {
      this.$apis
        .getFlowCompareData({ dealNo: this.selectRow.dealNo })
        .then((res) => {
          this.table.data = res.data.result.map((item) => {
            this.processItem.call(this, item);
            return item;
          });
        });
    },
    processItem(item) {
      // 检查并转换 formName
      const prefixes = ['field.', 'button.', 'form.', 'duration.'];
      if (item.formName && prefixes.some(prefix => item.formName.startsWith(prefix))) {
        item.formName = this.$t(item.formName);
      }
      // 如果有 children，递归处理
      if (Array.isArray(item.children)) {
        item.children.forEach((child) => this.processItem.call(this, child));
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.check-dialog {
  display: flex;
  .collapse {
    cursor: pointer;
    width: 100%;
    text-align: right;
    font-size: 24px;
  }
  .left-step {
    width: 300px;
    margin-right:5px;
    .step-list {
      overflow-y: auto;
    }
    .step-content {
      background: #aaa;
      border: 1px solid #aaa;
      padding: 10px;
      color: #fff;
      border-radius: 5px;
    }
    .step-handle {
      background: #2f3949;
      border: 1px solid #2f3949;
      color: #fff;
      border-radius: 5px;
      padding: 30px;
    }
  }
  .right-table {
    width: calc(100% - 305px);
    max-height: 600px;
  }
  .table-box {
    height: 100%;
  }
  .right-auto {
    width: 100%;
  }
}
</style>
