<template>
  <browser
      class="browser-businesss-table"
      :component-loading="componentLoading"
      :api-config="apiConfig"
      :table-config="tableConfig"
      :permissions="permissions"
      :dialog-config="dialogConfig"
      :default-query-params="queryParams"
      :actions="actions"
      @update:dialog-config="dialogConfig = $event"
      @update:actions="actions = $event">

    <template #queryPanel="{ queryParams: qp }">
      <el-form ref="queryForm" :model="qp" label-width="80px">
        <el-row class="query-condition">
          <el-col :span="6">
            <el-form-item label="执法机构" prop="agency">
              <AgencySelector :lazyLoad="true" v-model="qp.agency"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业名称" prop="unitName">
              <SimpleEnterpriseSelector v-model="qp.enterpriseId" :lazyLoad="true" :agencyId="qp.agency?.agencyId"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="当前节点" prop="currentNodeCode">
              <el-select v-model="qp.currentNodeCode" placeholder="请选择" clearable>
                <el-option
                    v-for="item in DICTITEMS.ZFJD_OPTIONS.filter(o => o.value !== 'plan_approval' && o.value !== 'plan_approval_failed')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="录入时间" prop="createTimeArr">
              <el-date-picker
                  v-model="qp.createTimeArr"
                  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 #tableControlColumn="{ data: r }">
      <el-link type="primary" @click="handleDetail(r.data.row)" title="立案">立案</el-link>
    </template>

    <template #dialogContent="{ dialogConfig: dc }">
      <el-collapse v-model="activeNames" v-if="dc.mode !== 'sampled'">
        <el-collapse-item name="1" title="方案基本信息">
          <fajbxx :dc="dc"/>
        </el-collapse-item>
        <el-collapse-item name="2" title="当事人及检查信息" v-if="dc.mode !== 'sampled'">
          <el-divider content-position="left">当事人信息</el-divider>
          <jczj :dc="dc" @on-dialog-loading="onDialogLoading" @on-modify-check-item="onModifyCheckItem"/>
        </el-collapse-item>
        <el-collapse-item name="3" title="整改复查" v-if="dc.data.enforcementInfo.rechecked === '11'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="复查日期" prop="checkReviewDate">
                <el-date-picker v-model="dc.data.checkReviewDate" type="date" placeholder="选择时间" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="复查人" prop="checkReviewer">
                <el-input v-model="dc.data.checkReviewer" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="复查意见" prop="checkReviewOpinion">
                <el-input type="textarea" :rows="5" v-model="dc.data.checkReviewOpinion" disabled/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
        <el-collapse-item name="3" title="现场处理措施" v-if="dc.data.enforcementInfo.rechecked === '21'">
          <el-col :span="24">
            <el-table ref="biaoge" :data="dc.data.xcclcstable" border style="min-height: 200px; overflow-y: auto">
              <el-table-column header-align="center" align="center" label="违法违规行为和事故隐患" prop="itemName" min-width="350"/>
              <el-table-column header-align="center" align="center" label="处理依据" min-width="250"  prop="enforcementBasis">
                <template #default="{ row }">
                  <el-input v-model="row.enforcementBasis" type="textarea" :rows="2" size="small" disabled/>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="24">
            <div style="margin-top: 10px">
              <!-- 动态渲染输入框列表 -->
              <div v-for="(input, index) in dc.data.xcclcscljd" :key="index">
                <el-form-item label="处理决定" prop="cljd">
                  <el-input  v-model="input.value" clearable disabled/>
                </el-form-item>
              </div>
            </div>
          </el-col>
        </el-collapse-item>
      </el-collapse>
      <jccy v-if="dc.mode === 'sampled'" :dc="dc" @on-dialog-loading="onDialogLoading" />
      <el-col :span="24">
        <el-form-item label-width="80px" label="是否立案" prop="fillingFlag">
          <el-radio-group v-model="dc.data.fillingFlag">
            <el-radio v-for="item in DICTITEMS.SF_OPTIONS" :key="item.value" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </template>
  </browser>
</template>

<script setup>
import browser from '@/components/Browser.vue'
import AgencySelector from '@/components/AgencySelector.vue'
import SimpleEnterpriseSelector from '@/components/SimpleEnterpriseSelector.vue'
import Jczj from '@pages/xzzfgl/jczj.vue'
import Jccy from '@pages/xzzfgl/jccy.vue'
import fajbxx from '@pages/xzzfgl/fajbxx.vue'
import {DICTITEMS} from '@/utils/Constants.js'
import {nextTick, onMounted, reactive, toRefs, watch} from 'vue'
import {useUserStore} from '@/stores/modules/user'
import enforcementInfo from '@/api/lawenforcement/EnforcementInfo.js'
import enforceChecks from '@/api/lawenforcement/EnforceChecks.js'
import {ElMessage} from 'element-plus'
import {useRoute} from 'vue-router'


const userStore = useUserStore()

const state = reactive({
  componentLoading: false,
  permissions: {
    query: true,
    add: false,
    modify: false,
    detail: false,
    delete: false,
    deleteAll: false,
    importFile: false,
    exportFile: false,
    exportSelectFile: false,
    downloadTemp: false,
  },
  tableConfig: {
    hasControlColumn: true,
    controlWidth: '120',
    multipleSelect: false,
  },
  apiConfig: {
    api: enforcementInfo,
    modelId: 'enforcementId',
  },
  dialogConfig: {
    formLabelWidth: '100px',
    show: false,
    mode: 'detail',
    title: '执行检查',
    loading: false,
    data: {
      enterprise: {},
      enforcementInfo: {},
    },
    actions: {
      handleDialogOk: handleDialogOk,
    },
    rules: {
      fillingFlag: [{required: true, message: '是否立案不能为空', trigger: 'change'}],
    },
  },
  actions: {
    detail: handleDetail,
  },
  queryParams: {
    fillingFlag: '0',
    recheckedArr: ['0', '11', '21', '3'],
    currentNodeCode: 'inspect_done',
    notCurrentNodeCode: 'plan_approval,plan_approval_failed',
    createTime: [],
  },
  delFileIds: [],
  filesData: [],
  pictureData: [],
  delPicIds: [],
  activeNames: ['3']
})

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

function handleDetail(row) {
  dialogConfig.value.mode = 'detail'
  dialogConfig.value.title = '检查详情'
  dialogConfig.value.showFooter = true
  findOne(row)
}

function findOne(row) {
  activeNames.value = ['3']
  dialogConfig.value.loading = true
  enforceChecks
      .findByEnforcementId(row.enforcementId)
      .then((rs) => {
        dialogConfig.value.loading = false
        if (rs.success) {
          filesData.value = []
          const target = rs.data
          dialogConfig.value.data = Object.assign({}, target, {
            agency: row.agency,
            enterprise: row.enterprise,
            officerIds: target.officerIds?.split(','),
            fillingFlag: target.enforcementInfo?.fillingFlag,
            writerId: target.writerId || userStore.userInfo.yhm,
            writerName: target.writerName || userStore.userInfo.xm,
          })
          let checkTime = []
          if (target.checkTimeStart) checkTime.push(target.checkTimeStart)
          if (target.checkTimeEnd) checkTime.push(target.checkTimeEnd)
          dialogConfig.value.data.checkTime = checkTime
          dialogConfig.value.show = true
        }
      })
      .catch(() => {
        dialogConfig.value.loading = false
      })
}

function handleDialogOk(formRef) {
  let data = Object.assign({}, dialogConfig.value.data)
  console.log(data)
  let param = {
    enforcementId: data.enforcementInfo.enforcementId,
    fillingFlag: data.fillingFlag
  }
  formRef.validate((valid) => {
    if (valid) {
      dialogConfig.value.loading = true
      enforcementInfo.updateFillingFlag(param)
          .then((res) => {
            if (res.success) {
              ElMessage.success('操作成功')
              dialogConfig.value.show = false
              actions.value.query()
            } else {
              throw new Error('操作失败')
            }
            dialogConfig.value.loading = false
          })
          .catch(() => {
            dialogConfig.value.loading = false
          })
    }
  })
}

function onDialogLoading(b) {
  dialogConfig.value.loading = b
}

function onModifyCheckItem(row) {
  dialogConfig.value.show = false
  nextTick(() => {
    dialogConfig.value.mode = 'check'
    dialogConfig.value.title = '执法检查'
    findOne(row)
  })
}

watch(
    () => dialogConfig.value.data.checkResult,
    (newVal) => {
      const baseRules = {
        officerIds: [{required: true, message: '执法人员不能为空', trigger: 'change'}],
        checkDate: [{required: true, message: '检查日期不能为空', trigger: 'change'}],
        checkTime: [{required: true, message: '检查时间不能为空', trigger: 'change'}],
        checkResult: [{required: true, message: '检查结果不能为空', trigger: 'change'}],
        fillingFlag: [{required: true, message: '是否立案不能为空', trigger: 'change'}],
        checkPlace: [
          {required: true, message: '检查场所不能为空', trigger: 'blur'},
          {min: 0, max: 200, message: '检查场所长度不能超过200', trigger: 'change'},
        ],
        remark: [{min: 0, max: 2000, message: '备注长度不能超过2000', trigger: 'change'}],
      }
      if (newVal) {
        if (newVal !== '1') baseRules.rectificationMeasures = [{required: true, message: '整改措施不能为空', trigger: 'blur'}]
        if (newVal === '3') baseRules.rectificationDate = [{required: true, message: '整改期限不能为空', trigger: 'change'}]
      }
      dialogConfig.value.rules = baseRules
    }
)
const route = useRoute();
onMounted(async () => {})
</script>

<style scoped lang="scss">
.zfjc-pic {
  .el-upload-list__item-thumbnail,
  .el-upload-list__item-actions,
  .el-upload-list__item,
  .el-upload--picture-card {
    width: 64px !important;
    height: 64px !important;
  }
}

:deep(.el-input) {
  width: 100%;
}

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

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

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

:deep(.el-input__inner) {
  -webkit-text-fill-color: #606266 !important;
}
</style>
