import axios from '@/common/services/axios-instance'
import pickValues from '@/common/services/pick-values'
import sdListPickerVue from '@/common/components/sd-list-picker.vue'
import AddressBook from '@/addressbook/group-user-service'
import { message } from '@/common/one-ui'

export default function({ button }) {
  return axios
    .get(`api/framework/v1/task-process/task/get-add-freesign-steps/${this.flowData.instId}`)
    .then((res) => {
      res.data.forEach((item) => (item.targetStepId = item.targetStepId + ''))
      let p
      if (res.data.length === 1) {
        p = Promise.resolve(res.data)
      } else {
        p = pickValues(sdListPickerVue, {
          optionLabel: 'targetStepName',
          optionValue: 'targetStepId',
          singleColumn: true,
          loadListData: () => res.data,
          single: true,
          title: '请选择自由环节',
        })
      }
      return p.then((step) => {
        if (step.length) {
          let p
          if (button.buttonId === 'workflow$addFreeSignOperator') {
            p = AddressBook.selectUser()
          } else {
            p = axios
              .get(
                `api/framework/v1/task-process/task/canbe-remove-freesign-operator/${this.flowData.instId}/${step[0].targetStepId}`
              )
              .then((res) => {
                return pickValues(sdListPickerVue, {
                  optionLabel: 'name',
                  optionValue: 'code',
                  singleColumn: true,
                  loadListData: () => res.data.taskOperator.map((item) => item.operators[0]),
                  single: false,
                  title: '请选择减签人员',
                })
              })
          }
          return p.then((user) => {
            if (user.length) {
              return axios
                .post(
                  `api/framework/v1/task-process/task/${
                    button.buttonId === 'workflow$addFreeSignOperator' ? 'add' : 'remove'
                  }-freesign-operators`,
                  {
                    instId: this.flowData.instId,
                    targetStepId: parseInt(step[0].targetStepId),
                    operators: user,
                    props: { source: 'WE.OFFICE' },
                  }
                )
                .then(() => {
                  message.success('处理成功')
                  return true
                })
            } else {
              message.warn('请选择人员')
            }
          })
        } else {
          message.warn('请选择环节')
        }
      })
    })
}
