<template>
  <div class="page">
    <edit-table
      ref="EditTable"
      v-model="data"
      :table-prop="tableProp"
      :fields="fields"
      :show-search-form="true"
      row-key="id"
      :search-form-prop="searchFormProp"
      :form-prop="formProp"
      :search-loader="searchLoader"
    />

    <!-- 选择市场主体弹窗 -->
    <el-dialog
      title="选择市场主体"
      :visible.sync="entDialogVisible"
      width="900px"
      :close-on-click-modal="false"
    >
      <div class="ent-search">
        <el-form :inline="true" :model="entSearchForm" class="search-form">
          <el-form-item label="统一社会信用代码">
            <el-input v-model="entSearchForm.uniscid" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="主体名称">
            <el-input v-model="entSearchForm.entname" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchEntList">查询</el-button>
            <el-button @click="resetEntSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        v-loading="entLoading"
        :data="entList"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#8cc3fb', color: '#fff' }"
      >
        <el-table-column prop="entname" label="主体名称" />
        <el-table-column prop="uniscid" label="统一社会信用代码" width="200" />
        <el-table-column prop="regno" label="注册号" width="150" />
        <el-table-column prop="regorgCn" label="登记机关" width="200" />
        <el-table-column label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="selectEnt(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px; text-align: right;"
        :current-page="entPagination.current"
        :page-sizes="[10, 20, 50]"
        :page-size="entPagination.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="entPagination.total"
        @size-change="handleEntSizeChange"
        @current-change="handleEntCurrentChange"
      />
    </el-dialog>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="formDialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="150px"
        :disabled="isView"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="市场主体名称" prop="entname">
              <el-input v-model="formData.entname" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="统一社会信用代码" prop="uniscid">
              <el-input v-model="formData.uniscid" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册号" prop="regno">
              <el-input v-model="formData.regno" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="tel">
              <el-input v-model="formData.tel" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="登记机关" prop="regOrgPath">
              <el-cascader
                v-model="formData.regOrgPath"
                :options="orgTreeList"
                :props="{ checkStrictly: true, value: 'id', label: 'label', children: 'children' }"
                :show-all-levels="false"
                placeholder="请选择"
                style="width: 100%;"
                clearable
                filterable
                @change="handleRegOrgChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="冒名登记事项" prop="regItem">
              <el-input v-model="formData.regItem" placeholder="请输入冒名登记事项" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="冒名登记时间" prop="regTime">
              <el-date-picker
                v-model="formData.regTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="处理原因" prop="handlRea">
              <el-select
                v-model="formData.handlRea"
                placeholder="请选择处理原因"
                style="width: 100%;"
                clearable
                filterable
                @change="handleHandlReaChange"
              >
                <el-option
                  v-for="item in handlReaOptions"
                  :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="handlRest">
              <el-input v-model="formData.handlRest" placeholder="请输入处理结果" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="公告内容" prop="noticeContent">
              <el-input
                v-model="formData.noticeContent"
                type="textarea"
                :rows="5"
                placeholder="请输入公告内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="作出决定机关" prop="judAuthPath">
              <el-cascader
                v-model="formData.judAuthPath"
                :options="orgTreeList"
                :props="{ checkStrictly: true, value: 'id', label: 'label', children: 'children' }"
                :show-all-levels="false"
                placeholder="请选择"
                style="width: 100%;"
                clearable
                filterable
                @change="handleJudAuthChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作出决定日期" prop="judDate">
              <el-date-picker
                v-model="formData.judDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告日期" prop="noticeDate">
              <el-date-picker
                v-model="formData.noticeDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公告期自" prop="noticeFrom">
              <el-date-picker
                v-model="formData.noticeFrom"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告期至" prop="noticeTo">
              <el-date-picker
                v-model="formData.noticeTo"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formDialogVisible = false">取 消</el-button>
        <el-button v-if="!isView" type="primary" @click="submitForm">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  nateOperCombinedListNateOperCombined,
  nateOperCombinedAddNateOperCombined,
  nateOperCombinedUpdateNateOperCombined,
  nateOperCombinedDeleteNateOperCombined,
  nateOperCombinedGetByIdId,
  eNateOperRegDecListEntBaseWithNateOperRegDec
} from '@/api/auto-baseapi.js'
import { getOrgTreeList, getConstant } from '@/api/system.js'

export default {
  name: 'RevokeDecisionAnnouncement',
  data() {
    return {
      data: [],
      tableProp: {
        emitLoadOnCreate: true,
        tableConfig: {
          showIndex: true,
          selection: false,
          indexWidth: '60px',
          handlerWidth: '150px',
          showPagination: true,
          tableProps: {
            headerCellStyle: { background: '#8cc3fb!important', color: '#fff!important', padding: '0px' },
            headerRowStyle: { height: '48px' },
            rowStyle: { height: '48px' },
            cellStyle: { padding: '16px 0', color: '#333' },
            rowClassName: (row) => {
              if (row.rowIndex % 2 === 1) {
                return 'warning-row'
              }
            }
          }
        },
        buttons: [
          {
            label: '编辑/查看',
            type: 'text',
            show: true,
            handler: (scope, { row }) => {
              this.handleEdit(row)
            }
          },
          {
            label: '删除',
            type: 'text',
            show: true,
            handler: (scope, { row }) => {
              this.handleDelete(row)
            }
          }
        ]
      },
      searchFormProp: {
        formConfig: {
          labelWidth: '120px',
          labelPosition: 'right',
          gutter: 32
        }
      },
      formProp: {
        formConfig: {
          labelWidth: '150px',
          labelPosition: 'right',
          gutter: 32,
          buttonPosition: 'right'
        }
      },
      fields: [
        {
          type: 'input',
          label: '统一社会信用代码',
          prop: 'uniscid',
          span: 6,
          showInForm: ({ meta }) => meta.isSearchForm === true,
          showInTable: false
        },
        {
          type: 'input',
          label: '主体名称',
          prop: 'entname',
          span: 6,
          showInForm: ({ meta }) => meta.isSearchForm === true,
          showInTable: false
        },
        {
          type: 'buttons',
          showInTable: false,
          showInForm: ({ meta }) => meta.isSearchForm === true,
          hiddenLabel: true,
          label: '搜索操作',
          prop: '搜索操作',
          span: 12,
          formItemProp: { labelWidth: '0px' },
          buttons: [
            {
              label: '查询',
              type: 'primary',
              handler: (scope) => {
                const { meta } = scope
                const { _editTable } = meta
                const { editTableInstance } = _editTable
                editTableInstance.search()
              }
            },
            {
              label: '重置',
              type: 'primary',
              buttonProps: { plain: true },
              handler: (scope) => {
                const { meta } = scope
                const { _editTable } = meta
                const { editTableInstance } = _editTable
                editTableInstance.search({ reset: true })
              }
            },
            {
              label: '增加',
              type: 'primary',
              handler: () => {
                this.handleAdd()
              }
            }
          ]
        },
        {
          type: 'input',
          label: '主体名称',
          prop: 'entname',
          showInForm: false
        },
        {
          type: 'input',
          label: '统一社会信用代码',
          prop: 'uniscid',
          showInForm: false
        },
        {
          type: 'input',
          label: '姓名',
          prop: 'name',
          showInForm: false
        },
        {
          type: 'input',
          label: '处理原因',
          prop: 'handlReaCn',
          showInForm: false
        },
        {
          type: 'input',
          label: '处理结果',
          prop: 'handlRest',
          showInForm: false
        },
        {
          type: 'input',
          label: '作出决定机关',
          prop: 'judAuthCn',
          showInForm: false
        },
        {
          type: 'input',
          label: '作出决定日期',
          prop: 'judDate',
          showInForm: false
        },
        {
          type: 'input',
          label: '公告日期',
          prop: 'noticeDate',
          showInForm: false
        }
      ],
      // 选择市场主体弹窗
      entDialogVisible: false,
      entLoading: false,
      entList: [],
      entSearchForm: {
        uniscid: '',
        entname: ''
      },
      entPagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 表单弹窗
      formDialogVisible: false,
      dialogTitle: '新增',
      isView: false,
      formData: {
        id: '',
        pripid: '',
        entname: '',
        uniscid: '',
        regno: '',
        name: '',
        tel: '',
        regOrg: '',
        regOrgCn: '',
        regOrgPath: [],
        regItem: '',
        regTime: '',
        handlRea: '',
        handlReaCn: '',
        handlRest: '',
        noticeContent: '',
        judAuth: '',
        judAuthCn: '',
        judAuthPath: [],
        judDate: '',
        noticeDate: '',
        noticeFrom: '',
        noticeTo: ''
      },
      formRules: {
        entname: [{ required: true, message: '请选择市场主体', trigger: 'change' }],
        uniscid: [{ required: true, message: '请选择市场主体', trigger: 'change' }],
        regno: [{ required: true, message: '请选择市场主体', trigger: 'change' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        tel: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
        regOrgPath: [{ required: true, message: '请选择登记机关', trigger: 'change' }],
        regItem: [{ required: true, message: '请输入冒名登记事项', trigger: 'blur' }],
        regTime: [{ required: true, message: '请选择冒名登记时间', trigger: 'change' }],
        handlRea: [{ required: true, message: '请选择处理原因', trigger: 'change' }],
        handlRest: [{ required: true, message: '请输入处理结果', trigger: 'blur' }],
        noticeContent: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
        judAuthPath: [{ required: true, message: '请选择作出决定机关', trigger: 'change' }],
        judDate: [{ required: true, message: '请选择作出决定日期', trigger: 'change' }],
        noticeDate: [{ required: true, message: '请选择公告日期', trigger: 'change' }],
        noticeFrom: [{ required: true, message: '请选择公告期自', trigger: 'change' }],
        noticeTo: [{ required: true, message: '请选择公告期至', trigger: 'change' }]
      },
      // 机关树形列表
      orgTreeList: [],
      // 处理原因选项
      handlReaOptions: []
    }
  },
  created() {
    this.loadOrgList()
    this.loadHandlReaOptions()
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.$nextTick(() => {
        if (vm.$refs.EditTable) {
          vm.$refs.EditTable.search({ reset: true })
        }
      })
    })
  },
  methods: {
    searchLoader(pageParam, parseSearchFormData) {
      return nateOperCombinedListNateOperCombined({
        size: pageParam.size,
        current: pageParam.current,
        entity: {
          ...parseSearchFormData
        }
      }).then((res) => {
        if (res.code === 0) {
          return {
            tableData: res.data.records || [],
            total: res.data.total || 0
          }
        } else {
          return {
            tableData: [],
            total: 0
          }
        }
      })
    },
    // 新增
    handleAdd() {
      this.entDialogVisible = true
      this.resetEntSearch()
      this.searchEntList()
    },
    // 编辑/查看
    handleEdit(row) {
      this.dialogTitle = '编辑/查看'
      this.isView = false
      nateOperCombinedGetByIdId({ id: row.id }).then((res) => {
        if (res.code === 0) {
          const data = res.data
          // 获取登记机关和作出决定机关的树形路径
          const regOrgPath = data.regOrg ? this.getPathById(this.orgTreeList, data.regOrg) : []
          const judAuthPath = data.judAuth ? this.getPathById(this.orgTreeList, data.judAuth) : []
          this.formData = {
            ...data,
            regOrgPath: regOrgPath || [],
            judAuthPath: judAuthPath || []
          }
          this.formDialogVisible = true
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除该记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        nateOperCombinedDeleteNateOperCombined({ id: row.id }).then((res) => {
          if (res.code === 0) {
            this.$message.success('删除成功')
            this.$refs.EditTable.search()
          }
        })
      })
    },
    // 选择市场主体后
    selectEnt(row) {
      this.entDialogVisible = false
      this.dialogTitle = '新增'
      this.isView = false
      // 获取登记机关的树形路径
      const regOrgPath = row.regorg ? this.getPathById(this.orgTreeList, row.regorg) : []
      this.formData = {
        id: '',
        pripid: row.pripid,
        entname: row.entname,
        uniscid: row.uniscid,
        regno: row.regno,
        name: '',
        tel: '',
        regOrg: row.regorg || '',
        regOrgCn: row.regorgCn || '',
        regOrgPath: regOrgPath || [],
        regItem: '',
        regTime: '',
        handlRea: '',
        handlReaCn: '',
        handlRest: '',
        noticeContent: '',
        judAuth: '',
        judAuthCn: '',
        judAuthPath: [],
        judDate: '',
        noticeDate: '',
        noticeFrom: '',
        noticeTo: ''
      }
      this.formDialogVisible = true
    },
    // 搜索市场主体
    searchEntList() {
      this.entLoading = true
      eNateOperRegDecListEntBaseWithNateOperRegDec({
        current: this.entPagination.current,
        size: this.entPagination.size,
        entity: {
          uniscid: this.entSearchForm.uniscid,
          entname: this.entSearchForm.entname
        }
      }).then((res) => {
        if (res.code === 0) {
          this.entList = res.data.records || []
          this.entPagination.total = res.data.total || 0
        } else {
          this.entList = []
          this.entPagination.total = 0
        }
      }).finally(() => {
        this.entLoading = false
      })
    },
    resetEntSearch() {
      this.entSearchForm = { uniscid: '', entname: '' }
      this.entPagination.current = 1
    },
    handleEntSizeChange(size) {
      this.entPagination.size = size
      this.searchEntList()
    },
    handleEntCurrentChange(current) {
      this.entPagination.current = current
      this.searchEntList()
    },
    // 登记机关变化
    handleRegOrgChange(val) {
      if (val && val.length > 0) {
        const lastId = val[val.length - 1]
        const node = this.findNodeById(this.orgTreeList, lastId)
        this.formData.regOrg = lastId
        this.formData.regOrgCn = node ? node.label : ''
      } else {
        this.formData.regOrg = ''
        this.formData.regOrgCn = ''
      }
    },
    // 作出决定机关变化
    handleJudAuthChange(val) {
      if (val && val.length > 0) {
        const lastId = val[val.length - 1]
        const node = this.findNodeById(this.orgTreeList, lastId)
        this.formData.judAuth = lastId
        this.formData.judAuthCn = node ? node.label : ''
      } else {
        this.formData.judAuth = ''
        this.formData.judAuthCn = ''
      }
    },
    // 在树形数据中查找节点
    findNodeById(tree, id) {
      for (const node of tree) {
        if (node.id === id) {
          return node
        }
        if (node.children && node.children.length > 0) {
          const found = this.findNodeById(node.children, id)
          if (found) return found
        }
      }
      return null
    },
    // 根据id获取从根到该节点的路径
    getPathById(tree, id, path = []) {
      for (const node of tree) {
        const currentPath = [...path, node.id]
        if (node.id === id) {
          return currentPath
        }
        if (node.children && node.children.length > 0) {
          const found = this.getPathById(node.children, id, currentPath)
          if (found) return found
        }
      }
      return null
    },
    // 加载机关列表
    loadOrgList() {
      getOrgTreeList().then(res => {
        if (res.code === 0) {
          this.orgTreeList = res.data || []
        }
      })
    },
    // 加载处理原因选项
    loadHandlReaOptions() {
      getConstant('CD96').then(res => {
        if (res.code === 0) {
          this.handlReaOptions = (res.data || []).map(item => ({
            value: item.code,
            label: item.name
          }))
        }
      })
    },
    // 处理原因变化
    handleHandlReaChange(val) {
      if (val) {
        const option = this.handlReaOptions.find(item => item.value === val)
        this.formData.handlReaCn = option ? option.label : ''
      } else {
        this.formData.handlReaCn = ''
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const api = this.formData.id
            ? nateOperCombinedUpdateNateOperCombined
            : nateOperCombinedAddNateOperCombined
          api(this.formData).then((res) => {
            if (res.code === 0) {
              this.$message.success('保存成功')
              this.formDialogVisible = false
              this.$refs.EditTable.search()
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/abnormal-list.scss";
.page {
  background: #fff;
  margin: 20px;
  padding: 20px;
}
.ent-search {
  margin-bottom: 15px;
}
</style>
