<template>
  <div class="page">
    <edit-table
      ref="EditTable"
      v-model="data"
      :table-prop="tableProp"
      :fields="fields"
      :show-search-form="true"
      row-key="falperId"
      :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="180px"
        :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="cerType">
              <el-select v-model="formData.cerType" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in certTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="证件号码" prop="cerNo">
              <el-input v-model="formData.cerNo" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="处理结果" prop="handlRest">
              <el-input
                v-model="formData.handlRest"
                type="textarea"
                :rows="3"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="处理原因" prop="handlRea">
              <el-select v-model="formData.handlRea" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in handleReasonOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <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-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-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 {
  eFalPerInfoListFalPerInfo,
  eFalPerInfoAddFalPerInfo,
  eFalPerInfoUpdateFalPerInfo,
  eFalPerInfoDeleteFalPerInfoFalperId,
  eFalPerInfoGetFalPerInfoByIdFalperId,
  eFalPerInfoListEntBaseWithFalPerInfo
} from '@/api/auto-baseapi.js'
import { getOrgTreeList } from '@/api/system.js'

export default {
  name: 'FalsePersonInfoAnnouncement',
  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: '180px',
          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: 'cascader',
          label: '作出决定机关',
          prop: 'judAuth',
          cnProp: 'judAuthCn',
          showInForm: ({ meta }) => meta.isSearchForm === true,
          formProps: {
            props: { checkStrictly: true, value: 'id', label: 'label', children: 'children' },
            'show-all-levels': false,
            clearable: true,
            filterable: true
          },
          options: () => this.orgTreeList,
          tableProps: {
            minWidth: '180px',
            showOverflowTooltip: true
          }
        },
        {
          type: 'date-picker',
          label: '作出决定日期',
          prop: 'judDate',
          showInForm: false,
          formProps: {
            valueFormat: 'yyyy-MM-dd'
          }
        }
      ],
      // 选择市场主体弹窗
      entDialogVisible: false,
      entLoading: false,
      entList: [],
      entSearchForm: {
        uniscid: '',
        entname: ''
      },
      entPagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 表单弹窗
      formDialogVisible: false,
      dialogTitle: '新增',
      isView: false,
      formData: {
        falperId: '',
        pripid: '',
        entname: '',
        uniscid: '',
        regno: '',
        name: '',
        cerType: '',
        cerNo: '',
        handlRest: '',
        handlRea: '',
        judAuth: '',
        judAuthCn: '',
        judAuthPath: [],
        judDate: ''
      },
      formRules: {
        name: [{ required: true, message: '请输入指定代表、委托代理人姓名', trigger: 'blur' }],
        cerType: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
        cerNo: [{ required: true, message: '请输入证件号码', trigger: 'blur' }],
        handlRest: [{ required: true, message: '请输入处理结果', trigger: 'blur' }],
        handlRea: [{ required: true, message: '请选择处理原因', trigger: 'change' }],
        judAuthPath: [{ required: true, message: '请选择作出决定机关', trigger: 'change' }],
        judDate: [{ required: true, message: '请选择作出决定日期', trigger: 'change' }]
      },
      // 证件类型选项
      certTypeOptions: [
        { value: '10', label: '中华人民共和国居民身份证' },
        { value: '20', label: '中华人民共和国军官证' },
        { value: '30', label: '中华人民共和国警官证' },
        { value: '40', label: '外国（地区）护照' },
        { value: '51', label: '香港特别行政区护照' },
        { value: '52', label: '香港（永久性）居民身份证' },
        { value: '53', label: '澳门特别行政区护照' },
        { value: '54', label: '澳门（永久性）居民身份证' },
        { value: '55', label: '港澳居民来往内地通行证' },
        { value: '56', label: '台湾居民身份证' },
        { value: '57', label: '台湾居民来往大陆通行证' },
        { value: '58', label: '台湾农民身份有关证明' },
        { value: '60', label: '户口簿' },
        { value: '61', label: '外国人永久居留身份证' },
        { value: '62', label: '华侨护照' },
        { value: '63', label: '港澳居民居住证' },
        { value: '64', label: '台湾居民居住证' },
        { value: '90', label: '其他有效身份证件' }
      ],
      // 处理原因选项
      handleReasonOptions: [
        { value: '101', label: '经登记机关调查认定冒名登记基本事实清楚的；' },
        { value: '102', label: '公司和相关人员无法取得联系或不配合调查且公示期内无利害关系人提出异议，登记机关认为冒名登记成立的' },
        { value: '103', label: '人民法院生效判决或裁定已认定冒名登记事实的' },
        { value: '199', label: '其他应当撤销登记的情形。' },
        { value: '201', label: '有证据证明被冒用人对该次登记知情或事后曾予追认' },
        { value: '202', label: '利害关系人在公示期内对撤销登记提出异议，经登记机关调查基本属实的；' },
        { value: '203', label: '公安、税务、金融、人力资源社会保障等相关部门出具书面意见不同意撤销登记' },
        { value: '204', label: '撤销登记可能对公共利益造成重大损害的' },
        { value: '299', label: '其他不应撤销登记的情形' }
      ],
      // 机关树形列表
      orgTreeList: []
    }
  },
  created() {
    this.loadOrgTreeList()
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.$nextTick(() => {
        if (vm.$refs.EditTable) {
          vm.$refs.EditTable.search({ reset: true })
        }
      })
    })
  },
  methods: {
    searchLoader(pageParam, parseSearchFormData) {
      return eFalPerInfoListFalPerInfo({
        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
      eFalPerInfoGetFalPerInfoByIdFalperId({ falperId: row.falperId }).then((res) => {
        if (res.code === 0) {
          const data = res.data
          // 获取作出决定机关的树形路径
          const judAuthPath = data.judAuth ? this.getPathById(this.orgTreeList, data.judAuth) : []
          this.formData = {
            ...data,
            judAuthPath: judAuthPath || []
          }
          this.formDialogVisible = true
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除该记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        eFalPerInfoDeleteFalPerInfoFalperId({ falperId: row.falperId }).then((res) => {
          if (res.code === 0) {
            this.$message.success('删除成功')
            this.$refs.EditTable.search()
          }
        })
      })
    },
    // 选择市场主体后
    selectEnt(row) {
      this.entDialogVisible = false
      this.dialogTitle = '新增'
      this.isView = false
      this.formData = {
        falperId: '',
        pripid: row.pripid,
        entname: row.entname,
        uniscid: row.uniscid,
        regno: row.regno,
        name: '',
        cerType: '',
        cerNo: '',
        handlRest: '',
        handlRea: '',
        judAuth: '',
        judAuthCn: '',
        judAuthPath: [],
        judDate: ''
      }
      this.formDialogVisible = true
    },
    // 搜索市场主体
    searchEntList() {
      this.entLoading = true
      eFalPerInfoListEntBaseWithFalPerInfo({
        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()
    },
    // 作出决定机关变化
    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
    },
    // 加载机关树形列表
    loadOrgTreeList() {
      getOrgTreeList().then(res => {
        if (res.code === 0) {
          this.orgTreeList = res.data || []
        }
      })
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const api = this.formData.falperId
            ? eFalPerInfoUpdateFalPerInfo
            : eFalPerInfoAddFalPerInfo
          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>
