<template>
  <div>
    <sd-workflow-push ref="actionComponent" />
    <a-modal
      destroy-on-close
      title="请选择"
      :width="800"
      :mask-closable="false"
      :visible="showSubOperator"
      :confirm-loading="confirmLoading"
      @ok="okClick"
      @cancel="() => (showSubOperator = false)"
    >
      <div>
        <a-card
          v-for="(item, index) in curStepsInfoClass"
          :key="index"
          :title="item.name"
          size="small"
        >
          <template slot="extra">
            <a-checkbox
              :indeterminate="isIndeterminate(item)"
              :checked="isCheckAll(item)"
              @change="(e) => onCheckAllChange(e, item)"
            >
              全选
            </a-checkbox>
          </template>
          <a-checkbox
            v-for="_ in item.operators"
            :key="_.value"
            :checked="subOperators.includes(_.value)"
            @change="(e) => onCheckChange(e, _.value)"
          >
            {{ _.label }}
          </a-checkbox>
        </a-card>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { Message, Modal } from 'ant-design-vue'
import pickValues from '@/common/services/pick-values'
import sdListPickerVue from '@/common/components/sd-list-picker.vue'
import { router } from '@/common/router-ready'
import FlowService from '../flow-service'
import components from './_import-components/sd-workflow-remove-sub-flow-operator-import'
import buttonHandlers from './index'
export default {
  name: 'SdWorkflowRemoveSubFlowOperator',

  components: {
    ...components,
    'sd-workflow-push': buttonHandlers.vue.sdworkflowpush,
  },
  data() {
    return {
      removeOperators: [],
      operators: [],
      operator: '',
      originLength: 0,
      showSubOperator: false,
      confirmLoading: false,
      subOperators: [],
    }
  },
  computed: {
    curStepsInfoClass() {
      const infos = []
      ;(this.operators || []).forEach((item) => {
        let info = infos.find((_) => _.name === item.attrs?.['propagate_branch_name'])
        if (!info) {
          info = { name: item.attrs?.['propagate_branch_name'], operators: [] }
          infos.push(info)
        }
        info.operators.push({
          label: item.name,
          value: info.name + '_' + item.code,
          origin: { ...item },
        })
      })
      return infos
    },
  },
  methods: {
    run({ button }) {
      let operator = 'removeOperator'
      if (button.buttonId === 'workflow$removeSubFlowOperator') {
        operator = 'subRemoveOperator'
      }
      this.operator = operator
      return FlowService.operators(this.webflow.flowData, button.buttonId).then((data) => {
        this.originLength = data.length // 处理的未处理的所有人
        data = data.filter((item) => item.status !== 'COMPLETED')
        if (data.length === 0) {
          Message.warn('未获取到待减签人员')
          return
        }
        this.operators = data
        // 主协办减签
        if (button.attrs?.mainSponsorStep === 'true') {
          this.subOperators = []
          this.showSubOperator = true
        } else {
          return pickValues(sdListPickerVue, {
            optionValue: 'code',
            optionLabel: 'name',
            loadListData: () => this.operators,
            singleColumn: true,
          }).then((data) => {
            if (!data) {
              return
            }
            if (data?.length === 0) {
              Message.warn('请选择减签人员')
              return
            }
            return this.submit(data)
          })
        }
      })
    },
    submit(data) {
      this.removeOperators = data
      if (
        // 选中所有可选的减签人员
        this.operator === 'subRemoveOperator' &&
        this.removeOperators.length === this.operators.length
      ) {
        if (
          this.operators.length === this.originLength &&
          this.operators.every((item) => item.status === 'QUEUED')
        ) {
          // 所有可减签的人员，全是未开始的，且没有过已完成的会签，走撤回
          return FlowService.encancel(this.webflow.flowData, {
            actionId: 'removeSubflowOperator',
          }).then((res) => {
            Message.success({ content: '已减签' }).then(() => {
              router.replace(`/sd-webflow/todo-pages/${res}`)
            })
          })
        } else {
          return FlowService.actions(this.webflow.flowData).then((data) => {
            data = data.filter((item) => item.actionId.indexOf('save') === -1) // 过滤掉保存按钮
            return pickValues(sdListPickerVue, {
              optionValue: 'actionId',
              optionLabel: 'buttonName',
              loadListData: () => data,
              singleColumn: true,
              single: true,
            }).then((node) => {
              node[0].buttonId = node[0].actionId
              return this.$refs.actionComponent.run({
                button: node[0],
                action: 'toaction',
                removeOperators: this.removeOperators,
              })
            })
          })
        }
      } else {
        let p = Promise.resolve(true)
        if (
          this.operator === 'removeOperator' &&
          this.removeOperators.length === this.operators.length &&
          this.originLength !== this.operators.length
        ) {
          // 并发审批选择所有可减签的人，但是有已经已完审批的人，则提示
          p = new Promise(function(resolve, reject) {
            Modal.confirm({
              content: '是否回到并发多人发起环节',
              onOk() {
                resolve(true)
              },
              onCancel() {
                const p = '取消减签'
                reject(p)
              },
            })
          })
        }
        return p.then(() => {
          return FlowService[this.operator](
            this.webflow.FlowData,
            this.removeOperators,
            this.webflow.getFormData()
          ).then((data) => {
            Message.success('已减签').then(() => {
              if (!data?.data || isNaN(data?.data)) {
                this.webflow.updateFlow()
              } else {
                router.replace(`/sd-webflow/todo-pages/${data?.data}`)
              }
            })
            return true
          })
        })
      }
    },
    isIndeterminate(item) {
      // 从选中的值中获取当前分类下的选中值
      const curSelecteds = this.subOperators.filter((value) => value.startsWith(item.name + '_'))
      return curSelecteds.length > 0 && curSelecteds.length < item.operators.length
    },
    isCheckAll(item) {
      const curSelecteds = this.subOperators.filter((value) => value.startsWith(item.name + '_'))
      return curSelecteds.length === item.operators.length
    },
    onCheckAllChange(e, item) {
      if (e.target.checked) {
        item.operators.forEach((operator) => {
          if (!this.subOperators.includes(operator.value)) {
            this.subOperators.push(operator.value)
          }
        })
      } else {
        this.subOperators = this.subOperators.filter((value) => !value.startsWith(item.name + '_'))
      }
    },
    onCheckChange(e, value) {
      if (e.target.checked) {
        this.subOperators.push(value)
      } else {
        this.subOperators = this.subOperators.filter((_) => _ !== value)
      }
    },
    okClick() {
      if (this.subOperators.length === 0) {
        Message.warn('请选择减签人员')
      } else {
        const data = []
        this.curStepsInfoClass.forEach((item) => {
          item.operators.forEach((_) => {
            if (this.subOperators.includes(_.value)) {
              data.push(_.origin)
            }
          })
        })
        this.confirmLoading = true
        this.submit(data).finally(() => {
          this.showSubOperator = false
          this.confirmLoading = false
        })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
