<template>
  <a-modal
    :destroy-on-close="true"
    title="选择编号"
    :body-style="{ overflow: 'auto' }"
    :width="800"
    :visible="modalVisible"
    :confirm-loading="confirmLoading"
    :ok-button-props="{ props: { disabled: okDisabled } }"
    @ok="handleOk"
    @cancel="() => (modalVisible = false)"
  >
    <a-tabs v-model="activeKey" type="card" @change="tabChange">
      <a-tab-pane v-for="tab in tabList" :key="tab.key" :tab="tab.label">
        <a-list
          bordered
          :data-source="tab.data"
          size="small"
          :class="$style.bhlist"
          :loading="tab.loading"
        >
          <div v-if="skipShowMore && activeKey === '0'" slot="loadMore" :class="$style.morebtn">
            <a-spin v-if="skipLoadingMore" />
            <a-button v-else @click="loadMoreSkipnumber">
              加载更多
            </a-button>
          </div>
          <a-list-item
            slot="renderItem"
            slot-scope="item"
            :class="[$style.bhlistitem, tab.isRowSelected(item.currentNumber) ? $style.active : '']"
            @click="selectorClick(item)"
          >
            {{ item.currentNumber }}
            <span v-if="tab.isRowSelected(item.currentNumber)" :class="$style.activeicon">
              <a-icon type="check" />
            </span>
          </a-list-item>
        </a-list>
      </a-tab-pane>
      <div v-show="activeKey === '0'" slot="tabBarExtraContent">
        <a-checkbox :checked="checkAll" @change="onSkipChange">
          跳号选择
        </a-checkbox>
      </div>
    </a-tabs>
    <div v-if="selectedNumbering.value" :class="$style.selectNumberWrapper">
      <span>已选择: {{ numberStylePre }} </span>
      <a-input-number v-model="inputNumberValue" class="sd-shrinking-input" />
      {{ numberStyleSuffix }}
    </div>
  </a-modal>
</template>

<script>
import { Modal } from 'ant-design-vue'
import FlowService from '../flow-service'
import components from './_import-components/sd-workflow-manual-number-import'

export default {
  name: 'SdWorkflowManualNumber',
  metaInfo: {
    title: '手动编号',
  },
  components,
  data() {
    return {
      modalVisible: false,
      selectedNumbering: {}, // 选择的编号
      activeKey: '0',
      tabList: [
        {
          key: '0',
          label: '流水号',
          data: [],
          initd: false,
          loading: false,
          isRowSelected: this.isSelected,
          loadData: this.getLsh,
        },
        {
          key: '1',
          label: '预留号',
          data: [],
          initd: false,
          loading: false,
          isRowSelected: this.isSelected,
          loadData: this.getReservednumber,
        },
        {
          key: '2',
          label: '漏号',
          data: [],
          initd: false,
          loading: false,
          isRowSelected: this.isSelected,
          loadData: this.getReservednumber,
        },
      ],
      confirmLoading: false,
      checkAll: false,
      numberStylePre: '',
      numberStyleSuffix: '',
      inputNumberValue: '', // 用户填写的流水号
      maxResults: 5,
      skipShowMore: false,
      skipLoadingMore: false,
    }
  },
  computed: {
    // 选择编号后才可以点击确定
    okDisabled() {
      return !this.selectedNumbering.serialNum
    },
    businessTypeId() {
      return (
        (this.webflow.FlowData?.processFormData?.processFormPropertyValues || []).find(
          (item) => item.name === 'businessTypeId'
        )?.value || ''
      )
    },
  },
  methods: {
    run({ button }) {
      const { formId, pageId } = this.webflow.FlowData?.processFormData
      this.formData = {
        formId,
        pageId,
        instId: this.webflow.FlowData?.instId,
        inputs: this.webflow.getBackendValues(),
      }
      // 默认选中第一个页签
      const tab = this.tabList[0]
      this.activeKey = tab.key
      if (!tab.initd) {
        tab.loadData()
      } else {
        this.selectedNumbering = {}
        if (tab.data.length) {
          this.selectorClick(tab.data[0])
        }
      }
      this.modalVisible = true
    },
    tabChange(key) {
      const tab = this.tabList[key]
      if (!tab.initd) {
        tab.loadData()
      } else {
        this.selectedNumbering = {}
        if (tab.data.length) {
          this.selectorClick(tab.data[0])
        }
      }
    },
    // 点击选择文号
    selectorClick(item) {
      this.selectedNumbering = {
        value: item.currentNumber,
        configId: item.configId,
        serialNum: item.currentSerial,
        numberStyle: item.numberStyle,
        orgLevelId: item.orgLevelId,
        initValue: item.initValue,
      }
      this.numberStylePre = item.serialLeft
      this.numberStyleSuffix = item.serialRight
      // 给输入框默认值，可以手动修改编号数字
      this.inputNumberValue = item.currentSerial
    },
    isSelected(item) {
      return this.selectedNumbering.value === item
    },
    // 获取流水号
    getLsh() {
      const tab = this.tabList[0]
      tab.loading = true
      FlowService.getLsh({
        businessTypeId: this.businessTypeId,
        instId: this.webflow.FlowData?.instId,
        currentNumber: this.webflow.getFieldValue?.('currentNumber'),
        ...this.formData,
      })
        .then((res) => {
          if (res.status === 200) {
            tab.data = res.data.data ?? []
            // 默认选中第一个
            if (tab.data.length) {
              this.selectorClick(tab.data[0])
            }
          }
        })
        .finally(() => {
          tab.initd = true
          tab.loading = false
        })
    },
    // 获取预留号、漏号；recordType：1预留号，2漏号
    getReservednumber() {
      const tab = this.tabList[this.activeKey]
      tab.loading = true
      FlowService.getReservednumber({
        businessTypeId: this.businessTypeId,
        recordType: Number(this.activeKey),
        ...this.formData,
      })
        .then((res) => {
          if (res.status === 200) {
            tab.data = res.data.data ?? []
            this.selectedNumbering = {}
            if (tab.data.length) {
              this.selectorClick(tab.data[0])
            }
          }
        })
        .finally(() => {
          tab.initd = true
          tab.loading = false
        })
    },
    handleOk() {
      const result = parseInt(this.inputNumberValue) - this.selectedNumbering.serialNum
      // 用户手动修改编号提示用户跳号会产生漏号
      if (result > 0) {
        Modal.confirm({
          title: '提示',
          content: `此修改会产生${result}条漏号，确认执行修改吗？`,
          onOk: () => {
            this.confirmLoading = true
            this.submitNumber()
          },
          onCancel: () => {},
        })
        // 正常编号
      } else {
        this.confirmLoading = true
        this.submitNumber()
      }
    },
    onSkipChange(e) {
      if (e.target.checked) {
        this.checkAll = true
        this.getSkipnumber()
      } else {
        this.checkAll = false
        this.skipShowMore = false
        this.getLsh()
      }
    },

    // 获取跳号
    getSkipnumber() {
      const tab = this.tabList[0]
      tab.loading = true
      const params = {
        businessTypeId: this.businessTypeId,
        currentNumber: this.selectedNumbering.value,
        currentSerial: this.selectedNumbering.serialNum,
        startValue: 1,
        maxResults: this.maxResults,
        ...this.formData,
      }
      FlowService.getSkipnumber(params)
        .then((res) => {
          if (res.status === 200) {
            const data = res.data.data ?? []
            if (data.length > 0) {
              tab.data = tab.data.concat(data)
              this.skipShowMore = true
            } else {
              tab.data = []
              this.skipShowMore = false
            }
          }
        })
        .finally(() => {
          tab.loading = false
        })
    },
    loadMoreSkipnumber() {
      this.skipLoadingMore = true
      const tab = this.tabList[0]
      const params = {
        businessTypeId: this.businessTypeId,
        currentNumber: this.selectedNumbering.value,
        currentSerial: this.selectedNumbering.serialNum,
        startValue: tab.data[tab.data.length - 1].currentSerial + 1,
        maxResults: this.maxResults,
        ...this.formData,
      }
      FlowService.getSkipnumber(params)
        .then((res) => {
          if (res.status === 200) {
            this.skipLoadingMore = false
            const data = res.data.data ?? []
            tab.data = tab.data.concat(data)
            if (data.length < this.maxResults) {
              this.skipShowMore = false
            }
          }
        })
        .finally(() => {
          this.skipLoadingMore = false
        })
    },
    // 校验编号
    submitNumber() {
      const params = {
        currentNumber: this.selectedNumbering.value,
        configId: this.selectedNumbering.configId,
        currentSerial: this.inputNumberValue,
        numberStyle: this.selectedNumbering.numberStyle,
        orgLevelId: this.selectedNumbering.orgLevelId,
        initValue: this.selectedNumbering.initValue,
        ...this.formData,
      }

      FlowService.checkNumberStyle(params)
        .then((res) => {
          this.confirmLoading = false
          this.webflow.setFieldValue('currentNumber', res.data.currentNumber)
          this.modalVisible = false
        })
        .catch((err) => {
          this.confirmLoading = false
          Modal.error({
            title: '编号失败',
            content: err.response?.data?.message || '编号失败',
          })
        })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.bhlist {
  height: 200px;
  overflow: auto;
  :global(.ant-spin-nested-loading > div > .ant-spin .ant-spin-dot) {
    margin-top: 80px;
  }
}
.morebtn {
  height: 40px;
  padding: 4px 0;
  text-align: center;
}
.bhlistitem:hover {
  background-color: $primary-1;
}
.active {
  background-color: $primary-1;
}
.activeicon {
  float: right;
  color: $primary-color;
}
.select-number-wrapper {
  margin-top: 12px;
}
</style>
