<template>
  <a-card :bordered="false">
    <x-form-table
      title="我的工单"
      ref="xFormTable"
      :queryParamsName="queryParamsName"
      :fixed-query-form="{
        users_f_handler_id: currUser.id,
      }"
      @action="toDetail">
      <template slot="button">
        <a-button @click="addApply">
          <a-icon type="plus"/>
          发起报建
        </a-button>
      </template>
    </x-form-table>
    <a-modal
      v-model="applyAddFlag"
      :footer="null"
      :dialog-style="{ top: '5rem' }"
      :z-index="1001"
      title="发起报建"
      :destroyOnClose="true">
      <x-add-native-form ref="xForm" @onSubmit="applySubmit"/>
    </a-modal>
    <WorkflowDetail
      ref="workFlow"
      @success="success"
      @nextClick="nextClick"
      @x-form-item-emit-func="handleFormItemEvent"
    >
    </WorkflowDetail>
    <address-select ref="addressSelect" @setAddress="setForm"></address-select>
    <!--  协议作废功能  -->
    <a-modal
      v-model="formState"
      :dialog-style="{ top: '5rem' }"
      :z-index="1001"
      title="作废"
      :destroyOnClose="true"
      width="55vw">
      <x-add-native-form
        ref="xCancelForm"
        @onSubmit="submit"
      />
      <template #footer>
        <a-button key="back" @click="formState = false">取消</a-button>
        <a-button key="submit" type="primary" :loading="submitLoading" @click="formSubmit">确认</a-button>
      </template>
    </a-modal>
  </a-card>
</template>

<script>
import WorkflowDetail from '@vue2-client/pages/WorkflowDetail/WorkflowDetail.vue'
import XFormTable from '@vue2-client/base-client/components/common/XFormTable/XFormTable'
import XAddNativeForm from '@vue2-client/base-client/components/common/XAddNativeForm/XAddNativeForm.vue'
import { getConfigByName, runLogic } from '@vue2-client/services/api/common'
import { mapState } from 'vuex'
import AddressSelect from '@vue2-client/pages/addressSelect/index.vue'

export default {
  name: 'Apply',
  components: {
    XFormTable,
    XAddNativeForm,
    WorkflowDetail,
    AddressSelect
  },
  provide () {
    return {
      generalFunction: {
        setCancel: this.setCancel,
      }
    }
  },
  data () {
    return {
      // 查询配置文件名
      queryParamsName: 'ApplyProcessCRUD',
      // 发起报建弹框控制
      applyAddFlag: false,
      formState: false,
      submitLoading: false,
      cancelRecord: {}
    }
  },
  computed: {
    ...mapState('account', { currUser: 'user' }),
  },
  methods: {
    addApply () {
      console.log('打开了吗')
      this.applyAddFlag = true
      this.$nextTick(
        () => {
          getConfigByName('addApplyForm', 'af-apply', (res) => {
            this.$refs.xForm.init({
              businessType: '新增',
              title: '发起报建',
              ...res
            })
          })
        }
      )
    },
    applySubmit (formData) {
      runLogic('addApply', formData).then(
        res => {
          this.$message.success('发起报建成功')
          this.$refs.xFormTable.refreshTable(true)
          this.applyAddFlag = false
        }
      ).catch(() => {
        this.applyAddFlag = false
      })
    },
    success () {
      console.log('完工')
    },
    toDetail (record, id) {
      this.$refs.workFlow.init({
        workflowId: record.ab_f_workflow_id,
        stepId: record.ws_f_step_id
      })
    },
    handleFormItemEvent (func, data, value) {
      console.log('打印一下：', func, data, value)
      if (func === 'selectAddress') {
        this.$refs.addressSelect.setFormShow()
      }
    },
    setForm (record) {
      this.$refs.workFlow.setFormValue({ address: record.f_address, address_id: record.f_address_id })
    },
    nextClick ({ form, formStep, workflowId }) {
      console.log('success', form, formStep, workflowId)
      const data = {
        workflowId,
        form,
        formStep
      }
      runLogic('applySubmitAfter', data, 'af-apply').then(
        res => {
          if (res) {
            // this.$message.success('提交成功！')
            this.$refs.xFormTable.refreshTable(true)
          }
        }
      )
    },
    // 协议作废
    setCancel (record) {
      this.cancelRecord = record
      this.formState = true
      this.$nextTick(() => {
        getConfigByName('setCancelForm', 'af-apply', (config) => {
          if (this.$refs.xCancelForm) {
            this.$refs.xCancelForm.init({
              formItems: config.formJson,
              title: '补充协议作废',
              businessType: '修改',
              showSubmitBtn: false,
              ...config
            })
            if (this.$refs.xCancelForm) {
              console.log(record)
              // this.$refs.xCancelForm.setForm(recordData)
            }
          } else {
            console.error('xCancelForm组件未加载完成')
            // 延迟重试
            setTimeout(() => {
              this.setCancel(record)
            }, 100)
          }
        })
      })
    },
    async formSubmit () {
      this.submitLoading = true
      const formData = await this.$refs.xCancelForm.asyncSubmit()
      try {
        await this.submit(formData)
      } catch (error) {
        this.$message.error('表单验证失败，请检查填写内容')
      } finally {
        this.submitLoading = false
      }
    },
    async submit (formData) {
      const data = {
        ...formData,
      }
      console.log('==formData', data)
      await runLogic('暂时没有实现的logic', data, 'af-apply').then(() => {
        this.$message.success('操作成功')
        this.formState = false
      })
    }
  }
}
</script>
