<template>
  <browser class="browser-businesss-table"
           :component-loading="componentLoading"
           :api-config="apiConfig"
           :table-config="tableConfig"
           :permissions="permissions"
           :dialog-config="dialogConfig"
           :actions="actions"
           :customQuery="true"
           @custom-query="handleQuery"
           @update:dialog-config="dialogConfig = $event"
           @update:actions="actions = $event">

    <template #queryPanel="{ queryParams: queryParams }">
      <el-form ref="queryForm" :model="queryParams" label-width="80px">
        <el-row class="query-condition">
          <el-col :span="6">
            <el-form-item label="执法机构" prop="agency">
              <agency-selector :lazyLoad="true" v-model="queryParams.agency"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业名称" prop="unitName">
              <el-input v-model="queryParams.unitName" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="录入时间" prop="createTime">
              <el-date-picker v-model="queryParams.createTime"
                              type="datetimerange"
                              start-placeholder="开始时间"
                              end-placeholder="结束时间"
                              format="YYYY-MM-DD HH:mm:ss"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              :default-time="[new Date(2000, 2, 1, 0, 0, 0),
                              new Date(2000, 2, 1, 23, 59, 59)]"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <el-table-column prop="enterprise.unitName" label="企业" min-width="300"/>
    <el-table-column prop="enterprise.unifiedSocialCode" label="统一信用代码" min-width="200"/>
    <el-table-column prop="agency.agencyName" label="执法机构" min-width="200"/>
    <el-table-column prop="currentNode" label="当前节点" min-width="200"/>
    <el-table-column prop="createTime" label="录入时间" min-width="200"/>

    <template #dialog>
      <el-dialog class="business-dialog"
                 v-model="dialogConfig.show"
                 :show-close="false"
                 :append-to-body="true"
                 :top="'20px'"
                 :width="'1000px'">
        <template #header>
          <div class="cvi-dialog-header">
            <div class="cvi-dialog-header-title">
              <div class="dialog-line"></div>
              {{ dialogConfig.title }}
            </div>
            <i class="iconfont icon-zyyy_tcgb" @click="dialogConfig.actions.handleClose"></i>
          </div>
        </template>

        <el-form class="browser-businesss-table-dialog-form"
                 label-width="100px"
                 :model="dialogConfig.data"
                 :rules="dialogConfig.rules"
                 ref="formRef">
          <!--重新渲染-->
          <el-row v-if="dialogConfig.mode !== 'detail'" class="width-100">
            <el-col :span="12">
              <el-form-item label="方案名称" prop="enforcementName">
                <el-input v-model="dialogConfig.data.enforcementName" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="方案内容" prop="enforcementContent">
                <el-input v-model="dialogConfig.data.enforcementContent" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="方案依据" prop="enforcementBasis">
                <el-input v-model="dialogConfig.data.enforcementBasis" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="起止时间" prop="enforcementTime">
                <el-date-picker v-model="dialogConfig.data.enforcementTime"
                                type="daterange"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="执法机构" prop="agency">
                <agency-selector :lazyLoad="true" v-model="dialogConfig.data.agency" @node-change="resetData"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业名称" prop="enterpriseIds">
                <SimpleEnterpriseSelector v-model="dialogConfig.data.enterpriseIds"
                                          :agencyCode="dialogConfig.data.agency?.agencyCode"
                                          :defaultEnterpriseIds="defaultEnterpriseIds"
                                          :isShowAll="false"
                                          multiple/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检查类型" prop="checkType">
                <el-select v-model="dialogConfig.data.checkType" placeholder="请选择检查类型" clearable>
                  <el-option v-for="item in DICTITEMS.JCLX_OPTIONS" :key="item.value" :label="item.label"
                             :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检查事项" prop="checkItemIds">
                <simple-check-item-selector v-model="dialogConfig.data.checkItemIds"
                                            :lazyLoad="true"
                                            multiple/>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="dialogConfig.mode === 'add'">
              <el-form-item label="附件" prop="annex">
                <MultipleFile :parameters="fileParameters"
                              :files-data="dialogConfig.data.annexs"
                              @on-change="onChange"
                              @on-remove="onRemove"/>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="dialogConfig.mode === 'modify'">
              <el-form-item label="附件" prop="annex">
                <MultipleFile :parameters="fileParameters"
                              :files-data="dialogConfig.data.annexs"
                              @on-change="onChange"
                              @on-remove="onRemove"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="dialogConfig.mode === 'detail'" class="width-100">
            <el-divider content-position="left">基础信息</el-divider>
            <el-row class="width-100">
              <el-col :span="12">
                <el-form-item label="方案名称" prop="enforcementName1">
                  <el-input v-model="dialogConfig.data.enforcementName" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="方案内容" prop="enforcementContent1">
                  <el-input v-model="dialogConfig.data.enforcementContent" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="方案依据" prop="enforcementBasis1">
                  <el-input v-model="dialogConfig.data.enforcementBasis" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="起止时间" prop="enforcementTime1">
                  <el-input v-model="dialogConfig.data.enforcementTime" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="检查类型" prop="checkType1">
                  <el-select v-model="dialogConfig.data.checkType" placeholder="请选择检查类型" disabled>
                    <el-option v-for="item in DICTITEMS.JCLX_OPTIONS" :key="item.value" :label="item.label"
                               :value="item.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="执法机构" prop="agencyName">
                  <el-input v-model="dialogConfig.data.agency.agencyName" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业名称" prop="unitName">
                  <el-input v-model="dialogConfig.data.enterprise.unitName" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="统一信用代码" prop="unifiedSocialCode">
                  <el-input v-model="dialogConfig.data.enterprise.unifiedSocialCode" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="企业地址" prop="detailedAddress">
                  <el-input v-model="dialogConfig.data.enterprise.detailedAddress" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="附件" prop="annex">
                  <MultipleFile :parameters="fileParameters"
                                :files-data="dialogConfig.data.annexs"
                                @on-change="onChange"
                                @on-remove="onRemove"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider content-position="left">检查事项</el-divider>
            <el-row class="width-100">
              <el-col :span="24" class="padding-bottom-10">
                <el-table :data="dialogConfig.data.checkItems" height="300" border>
                  <el-table-column header-align="center" align="center" label="检查事项" prop="itemName" min-width="250"/>
                  <el-table-column header-align="center" align="center" label="执法依据" prop="enforcementBasis"
                                   min-width="250"/>
                  <el-table-column header-align="center" align="center" label="处罚依据" prop="punishmentBasis"
                                   min-width="250"/>
                </el-table>
              </el-col>
            </el-row>
          </el-row>
        </el-form>

        <template #footer v-if="dialogConfig.mode !== 'detail'">
          <div class="cvi-dialog-footer">
            <el-button @click="dialogConfig.actions.handleClose">取消</el-button>
            <el-button type="primary" @click="dialogConfig.actions.handleDialogOk">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </template>
  </browser>
</template>
<script setup>
import browser from '@/components/Browser.vue'
import AgencySelector from '@/components/AgencySelector.vue'
import SimpleEnterpriseSelector from '@/components/SimpleEnterpriseSelector.vue'
import SimpleCheckItemSelector from '@/components/SimpleCheckItemSelector.vue'
import MultipleFile from '@pages/common/MultipleFile.vue'
import {DICTITEMS} from '@/utils/Constants.js'
import messagesApi from '@/api/lawenforcement/Message.js'
import {reactive, ref, toRefs} from 'vue'
import enforcementInfo from '@/api/lawenforcement/EnforcementInfo'
import {ElMessage} from 'element-plus'

const state = reactive({
  componentLoading: false,
  permissions: {
    query: true,
    add: true,
    modify: true,
    detail: true,
    delete: true,
    deleteAll: true,
    importFile: false,
    exportFile: false,
    exportSelectFile: false,
    downloadTemp: false,
    canModifyCustom: (row) => row.currentNodeCode === 'plan_approval' || row.currentNodeCode === 'plan_approval_failed',
  },
  tableConfig: {
    hasControlColumn: true,
    controlWidth: '180'
  },
  apiConfig: {
    api: enforcementInfo,
    modelId: 'enforcementId',
  },
  dialogConfig: {
    show: false,
    mode: 'detail',
    title: '执法信息',
    loading: false,
    formLabelWidth: '100',
    multiple: true,
    data: {
      enterprise: {},
      agency: {},
      annexs: [],
    },
    actions: {
      handleClose: handleClose,
      handleDialogOk: handleDialogOk
    },
    rules: {
      // enforcementName: [{
      //   required: true,
      //   message: '方案名称不能为空',
      //   trigger: 'blur'
      // }],
      // enforcementContent: [{
      //   required: true,
      //   message: '方案内容不能为空',
      //   trigger: 'blur'
      // }],
      // enforcementBasis: [{
      //   required: true,
      //   message: '方案依据不能为空',
      //   trigger: 'blur'
      // }],
      enforcementTime: [{
        required: true,
        message: '起止时间不能为空',
        trigger: 'change'
      }],
      agency: [{
        required: true,
        message: '执法机构不能为空',
        trigger: 'change'
      }],
      enterpriseIds: [{
        required: true,
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (value?.length > 0) {
            callback()
          } else {
            callback(new Error('企业名称不能为空'))
          }
        }
      }],
      checkType: [{
        required: true,
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (value?.length > 0) {
            callback()
          } else {
            callback(new Error('检查类型不能为空'))
          }
        }
      }],
      checkItemIds: [{
        required: true,
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (value?.length > 0) {
            callback()
          } else {
            callback(new Error('检查事项不能为空'))
          }
        }
      }]
    },
  },
  fileParameters: {
    mode: 'add',
    required: false,
    title: '相关材料',
    tableTitle: '材料',
  },
  actions: {
    add: handleAdd,
    modify: handleModify,
    detail: handleDetail,
  },
  queryParams: {},
})

const {
  componentLoading,
  permissions,
  tableConfig,
  apiConfig,
  dialogConfig,
  fileParameters,
  actions,
  queryParams
} = toRefs(state)

// 分页查询
function handleQuery(queryParams) {
  queryParams.currentNodeCode = 'plan_approval,plan_approval_failed'
  queryParams.agencyCode = queryParams.agency?.agencyCode
  if (queryParams.createTime && queryParams.createTime.length === 2) {
    queryParams.startTime = queryParams.createTime[0]
    queryParams.endTime = queryParams.createTime[1]
  } else {
    queryParams.startTime = null
    queryParams.endTime = null
  }
  tableConfig.value.tableLoading = true
  apiConfig.value.api.query(queryParams).then(res => {
    if (res.success) {
      tableConfig.value.tableData = res
      tableConfig.value.tableLoading = false
    }
  })
}

function handleAdd() {
  fileParameters.value.mode = 'add'
  dialogConfig.value.mode = 'add'
  dialogConfig.value.title = '执法信息新增'
  dialogConfig.value.loading = false
  dialogConfig.value.data = {
    enterprise: {},
    agency: {},
    annexs: []
  }
  dialogConfig.value.show = true
}

// 文件组件上传成功回调
function onChange(data) {
  let tablezjcl = {
    uid: data.uid,
    name: data.name,
    type: data.name.split('.')[1],
    file: data.raw
  }
  dialogConfig.value.data.annexs.push(tablezjcl)
}

// 文件组件删除文件回调
function onRemove(fileList, id) {
  dialogConfig.value.data.annexs = fileList
}

function handleModify(row) {
  fileParameters.value.mode = 'detail'
  dialogConfig.value.mode = 'modify'
  dialogConfig.value.title = '执法信息修改'
  dialogConfig.value.loading = true
  dialogConfig.value.show = true
  findOne(row)
}

function handleDetail(row) {
  fileParameters.value.mode = 'detail'
  dialogConfig.value.mode = 'detail'
  dialogConfig.value.title = '执法信息详情'
  dialogConfig.value.loading = true
  dialogConfig.value.show = true
  findOne(row)
}

const defaultEnterpriseIds = ref([])

function findOne(row) {
  apiConfig.value.api.findOne(row.enforcementId).then(res => {
    dialogConfig.value.loading = false
    if (res.success) {
      const data = res.data
      // 处理机构信息
      if (!data.agency) data.agency = {}
      // 处理企业ID
      data.enterpriseIds = [data.enterpriseId].filter(Boolean)
      defaultEnterpriseIds.value = data.enterpriseIds
      // 方案时间
      data.enforcementTime = [data.enforcementStartTime, data.enforcementEndTime]
      // 检查类型
      data.checkType = data.enforceChecks[0].checkType
      // 处理检查项ID
      data.checkItemIds = data.checkItems.map(item => item.itemId)
      // 附件
      data.annexs.forEach(item => item.url = item.downloadUrl)
      // 响应式更新
      dialogConfig.value.data = Object.assign({}, data)
    } else {
      ElMessage.error('执法信息详情查询失败')
    }
  })
}

function handleClose() {
  dialogConfig.value.show = false
}

const formRef = ref()

function handleDialogOk() {
  let _event = actions.value
  formRef.value.validate(valid => {
    if (valid) {
      if (dialogConfig.value.mode === 'add') {
        dialogConfig.value.loading = true
        // params.append('enforcementName', dialogConfig.value.data.enforcementName)
        // params.append('enforcementContent', dialogConfig.value.data.enforcementContent)
        // params.append('enforcementBasis', dialogConfig.value.data.enforcementBasis)
        if (dialogConfig.value.data.enforcementName) params.append('enforcementName', dialogConfig.value.data.enforcementName)
        if (dialogConfig.value.data.enforcementContent) params.append('enforcementContent', dialogConfig.value.data.enforcementContent)
        if (dialogConfig.value.data.enforcementBasis) params.append('enforcementBasis', dialogConfig.value.data.enforcementBasis)
        params.append('enforcementTime', dialogConfig.value.data.enforcementTime)
        params.append('agencyId', dialogConfig.value.data.agency.agencyId)
        params.append('enterpriseIds', dialogConfig.value.data.enterpriseIds)
        params.append('checkType', dialogConfig.value.data.checkType)
        params.append('checkItemIds', dialogConfig.value.data.checkItemIds)
        dialogConfig.value.data.annexs.forEach(item => params.append('annexs', item.file))
        apiConfig.value.api.addEnforcementInfo(params)
            .then(res => {
              dialogConfig.value.loading = false
              if (res.success) {
                dialogConfig.value.show = false
                ElMessage.success('操作成功')
                messagesApi
                    .sendMessage({
                      title: '定制检查方案',
                      content: '您有一些待审批定制检查方案记录!',
                      routeUrl: '/xzzfgl/zfjc/fasp',
                      receiverIds: ['111111']
                    })
                    .then(res => console.log(res))
                _event.query()
              } else {
                throw new Error('操作失败')
              }
            })
      } else if (dialogConfig.value.mode === 'modify') {
        if (dialogConfig.value.data.enterpriseIds.length > 1) {
          ElMessage.error('只能选择一个企业！')
          return
        }
        // 清空附件
        dialogConfig.value.data.annexs = []
        // 检查记录id
        dialogConfig.value.data.enforceCheckId = dialogConfig.value.data.enforceChecks[0].enforceCheckId
        dialogConfig.value.loading = true
        apiConfig.value.api.modify(dialogConfig.value.data.enforcementId, dialogConfig.value.data)
            .then(res => {
              dialogConfig.value.loading = false
              if (res.success) {
                dialogConfig.value.show = false
                ElMessage.success('操作成功')
                _event.query()
              } else {
                throw new Error('操作失败')
              }
            })
      } else if (dialogConfig.value.mode === 'detail') {
        dialogConfig.value.show = false
      }
    }
  })
}

// 重置数据
function resetData() {
  dialogConfig.value.data.enterpriseIds = []
  defaultEnterpriseIds.value = []
}
</script>
<style lang="scss">
.pic-content {
  .el-upload-list__item-thumbnail, .el-upload-list__item-actions, .el-upload-list__item, .el-upload--picture-card {
    width: 64px !important;
    height: 64px !important;
  }
}
</style>
<style lang="scss" scoped>
.browser-businesss-table {
  .browser-businesss-table-dialog-form {
    padding: 10px 20px 10px 20px;
  }
}

.width-100 {
  width: 100%;
}

.padding-bottom-10 {
  padding-bottom: 10px;
}

:deep(.el-select__wrapper.is-disabled) {
  background: unset !important;
}

:deep(.el-select__wrapper.is-disabled .el-select__selected-item) {
  color: #606266 !important;
}
</style>
