<template>
  <div class="page">
    <easy-form
      ref="EasyForm"
      v-model="data"
      :fields="fields"
      :form-config="formConfig"
      :buttons="buttons"
    >
      <template v-slot:divider="scope">
        <div class="divider">
          <span class="text">{{ scope.getPropValue(scope.field.label) }}</span>
        </div>
      </template>
      <template v-slot:entListTable>
        <!-- 按钮组 -->
        <div class="button-group" style="margin-bottom: 10px; text-align: right;">
          <el-button type="primary" @click="$refs.entlist.open()">条件添加企业</el-button>
          <el-button type="primary" @click="importDialog = true">批量导入</el-button>
          <el-button type="danger" :disabled="selectedEnts.length === 0" @click="batchDelete">批量删除</el-button>
        </div>
        <easy-table
          ref="EntListTable"
          v-model="entListTableData"
          :fields="entListFields"
          :table-config="entListTableConfig"
          :emit-load-on-create="true"
          :on-load="loadEntListData"
          :selected.sync="selectedEnts"
        />
      </template>
    </easy-form>

    <!-- 批量导入弹窗 -->
    <el-dialog title="批量导入" :visible.sync="importDialog" width="30%">
      <el-upload
        :action="uploadPath"
        :data="{ taskListId: taskId }"
        :on-success="uploadCallback"
        :on-error="errorCallback"
        :before-upload="beforeUpload"
        accept=".xls,.xlsx"
        :show-file-list="false"
      >
        <el-button type="primary">上传文件</el-button>
      </el-upload>
      <div style="margin-top: 10px; color: #999;">支持 .xls、.xlsx 格式，文件大小不超过 10MB</div>
      <FakeProgress v-if="showFakeProgress" ref="FakeProgress" style="margin-top: 10px;" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialog = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 复用 EntList 组件 -->
    <EntList ref="entlist" type="todo" @confirm="onSelectEnt" />
  </div>
</template>

<script>
import EntList from '../component/EntList.vue'
import FakeProgress from '@/components/FakeProgress'
import {
  announcementTaskAdd,
  announcementTaskGetId,
  announcementTaskUpdate,
  announcementTaskDetailAdd,
  announcementTaskDetailDeleteId,
  announcementTaskDetailPage,
  announcementTaskDetailListTaskListId
} from '@/api/auto-baseapi'
import { xrForceDeregisterSpeSaveIvdAcceptNew } from '@/api/force'

export default {
  components: {
    EntList,
    FakeProgress
  },
  data() {
    return {
      isAddMode: this.$route.query.mode === 'add',
      taskId: this.$route.query.id || '',
      data: {},
      entListTableData: [],
      selectedEnts: [],
      importDialog: false,
      showFakeProgress: false,
      uploadPath: process.env.VUE_APP_BASE_API + '/announcement/task/detail/import',
      formConfig: {
        labelPosition: 'right',
        buttonPosition: 'right',
        gutter: 0
      },
      fields: [
        {
          type: 'divider',
          label: '任务名单信息'
        },
        {
          type: 'input',
          label: '任务名称',
          prop: 'taskName',
          required: true,
          span: 24
        },
        {
          type: 'input',
          label: '创建单位',
          prop: 'createUnitName',
          span: 12,
          isView: true,
          showInForm: () => !this.isAddMode
        },
        {
          type: 'input',
          label: '创建时间',
          prop: 'createTime',
          span: 12,
          isView: true,
          showInForm: () => !this.isAddMode
        },
        {
          type: 'input',
          label: '更新时间',
          prop: 'updateTime',
          span: 12,
          isView: true,
          showInForm: () => !this.isAddMode
        },
        {
          type: 'divider',
          label: '企业名录列表',
          showInForm: () => !this.isAddMode
        },
        {
          type: 'slot',
          slotName: 'entListTable',
          label: '企业名录列表',
          hiddenLabel: true,
          prop: 'entList',
          span: 24,
          showInForm: () => !this.isAddMode
        }
      ],
      entListFields: [
        {
          type: 'input',
          label: '统一社会信用代码/注册号',
          prop: 'uniscid',
          tableProps: {
            showOverflowTooltip: true,
            width: '220px',
            formatter: (row) => {
              return `${row.uniscid || row.regno || ''}`
            }
          }
        },
        {
          type: 'input',
          label: '主体名称',
          prop: 'entname',
          tableProps: {
            showOverflowTooltip: true,
            width: '300px'
          }
        },
        {
          type: 'input',
          label: '所属行业',
          prop: 'industryphy',
          optionsBaseCode: 'CA05',
          tableProps: {
            showOverflowTooltip: true
          }
        },
        {
          type: 'input',
          label: '吊销时间',
          prop: 'revoketime',
          tableProps: {
            showOverflowTooltip: true,
            width: '120px'
          }
        }
      ],
      entListTableConfig: {
        selection: true,
        tableSelectionProps: {
          reserveSelection: true
        },
        showIndex: true,
        indexWidth: '80px',
        showPagination: true,
        rowKey: 'id',
        tableProps: {
          headerCellStyle: { background: '#F5F5F5!important', color: '#333333!important', padding: '0px' },
          headerRowStyle: { height: '48px' },
          rowStyle: { height: '48px' },
          cellStyle: { padding: '16px 0', color: '#333' }
        },
        onSelectionChange: (selection) => {
          this.selectedEnts = selection
        },
        buttons: [
          {
            label: '删除',
            type: 'text',
            handler: (scope, { row }) => {
              this.deleteDetail(row)
            }
          }
        ]
      },
      buttons: [
        {
          label: '返回',
          type: 'primary',
          show: true,
          buttonProps: {
            plain: true
          },
          handler: () => {
            this.$router.back()
          }
        },
        {
          label: '保存并发起拟强制注销公告',
          type: 'primary',
          show: () => !this.isAddMode,
          handler: ({ formInstance }) => {
            return formInstance.submitForm().then((formData) => {
              return this.$confirm('发起拟强制注销公告后，当前名单无法修改，是否发起公告？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                confirmHandlerPromise: () => {
                  const savePromise = this.isAddMode
                    ? announcementTaskAdd({ taskName: formData.taskName }).then((res) => {
                      if (res.code === 0) {
                        this.taskId = res.data.id || res.data
                        this.isAddMode = false
                        return this.taskId
                      }
                      return Promise.reject('保存失败')
                    })
                    : announcementTaskUpdate({ id: this.taskId, taskName: formData.taskName }).then((res) => {
                      if (res.code === 0) return this.taskId
                      return Promise.reject('保存失败')
                    })

                  return savePromise.then(taskId => {
                    return announcementTaskDetailListTaskListId({ taskListId: taskId }).then(res => {
                      if (res.code === 0 && res.data && res.data.length > 0) {
                        const allEntList = res.data
                        return xrForceDeregisterSpeSaveIvdAcceptNew({
                          pripIdList: allEntList.map(item => item.pripid),
                          busType: 'inclusion'
                        }).then((data) => {
                          this.$message.success('保存并发起拟强制注销公告成功')
                          return this.$router.push({
                            path: '/forceNotice/inclusion/todo/handle',
                            query: { bizSeqNo: data.bizSeqId }
                          })
                        })
                      } else {
                        this.$message.warning('任务名单中没有企业，无法发起拟强制注销公告，仅保存成功')
                        if (!this.isAddMode) {
                          this.loadTaskInfo()
                        }
                        return Promise.reject()
                      }
                    })
                  })
                }
              })
            })
          }
        },
        {
          label: '保存',
          type: 'primary',
          show: true,
          handler: ({ formInstance }) => {
            return formInstance.submitForm().then((formData) => {
              if (this.isAddMode) {
                return announcementTaskAdd({
                  taskName: formData.taskName
                }).then((res) => {
                  if (res.code === 0) {
                    this.$message.success('任务名单创建成功')
                    const newId = res.data.id || res.data
                    this.$router.replace({
                      path: '/forceNotice/taskList/detail',
                      query: { id: newId }
                    })
                    this.taskId = newId
                    this.isAddMode = false
                    this.loadTaskInfo()
                  }
                })
              } else {
                return announcementTaskUpdate({
                  id: this.taskId,
                  taskName: formData.taskName
                }).then((res) => {
                  if (res.code === 0) {
                    this.$message.success('保存成功')
                  }
                })
              }
            })
          }
        }
      ]
    }
  },
  created() {
    if (!this.isAddMode && this.taskId) {
      this.loadTaskInfo()
    }
  },
  methods: {
    loadTaskInfo() {
      announcementTaskGetId({ id: this.taskId }).then((res) => {
        if (res.code === 0) {
          this.data = {
            ...this.data,
            ...res.data
          }
        }
      })
    },
    loadEntListData(pageParam) {
      if (!this.taskId) {
        return Promise.resolve({ tableData: [], total: 0 })
      }
      return announcementTaskDetailPage({
        size: pageParam.size,
        current: pageParam.current,
        entity: {
          taskListId: this.taskId
        }
      }).then((res) => {
        return {
          tableData: res.data.records,
          total: res.data.total
        }
      })
    },
    onSelectEnt(entlist) {
      if (entlist.length === 0) {
        this.$message.warning('请选择至少一个主体')
        return
      }
      announcementTaskDetailAdd({
        taskListId: this.taskId,
        pripidList: entlist.map(item => item.pripid)
      }).then((res) => {
        if (res.code === 0) {
          this.$message.success(`成功添加 ${entlist.length} 个主体`)
          this.$refs.EntListTable.reset()
        }
      })
    },
    deleteDetail(row) {
      this.$confirm('是否确定删除该企业？', '提示', {
        type: 'warning',
        confirmHandlerPromise: () => {
          return announcementTaskDetailDeleteId({ id: row.id }).then((res) => {
            if (res.code === 0) {
              this.$message.success('删除成功')
              this.$refs.EntListTable.reset()
            }
          })
        }
      })
    },
    batchDelete() {
      this.$confirm(`是否确定删除选中的 ${this.selectedEnts.length} 个企业？`, '提示', {
        type: 'warning',
        confirmHandlerPromise: () => {
          const promises = this.selectedEnts.map(item =>
            announcementTaskDetailDeleteId({ id: item.id })
          )
          return Promise.all(promises).then((resList) => {
            if (resList.every(res => res.code === 0)) {
              this.$message.success('批量删除成功')
            }
            this.selectedEnts = []
            this.$refs.EntListTable.reset()
          })
        }
      })
    },
    beforeUpload(file) {
      this.showFakeProgress = true
      return new Promise((resolve, reject) => {
        const testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'xls'
        const extension2 = testmsg === 'xlsx'
        if (!extension && !extension2) {
          this.$message.warning('上传文件只能是 xls、xlsx 格式！')
          this.showFakeProgress = false
          reject()
        } else {
          const isLt10M = file.size / 1024 / 1024 < 10
          if (!isLt10M) {
            this.$message.warning('上传文件大小不能超过 10MB！')
            this.showFakeProgress = false
            reject()
          } else {
            resolve()
          }
        }
      })
    },
    uploadCallback(res) {
      if (res.code === 0) {
        this.$refs.FakeProgress && this.$refs.FakeProgress.success()
        setTimeout(() => {
          this.importDialog = false
          this.showFakeProgress = false
          this.$message.success('导入成功')
          this.$refs.EntListTable.reset()
        }, 1000)
      } else {
        this.$refs.FakeProgress && this.$refs.FakeProgress.error()
        this.showFakeProgress = false
        this.$message.error(res.msg || '导入失败')
      }
    },
    errorCallback() {
      this.$refs.FakeProgress && this.$refs.FakeProgress.error()
      this.showFakeProgress = false
      this.$message.warning('上传文件失败，请检查文件格式或数据')
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/abnormal-handle";
.button-group {
  margin-bottom: 10px;
  text-align: right;
  .el-button {
    margin-left: 10px;
  }
}
</style>
