<template>
  <div class="role-div">
    <Tabs type="card" ref="tabs" style="height: 100%" v-model="tabValue" @on-click="changeTab">
      <TabPane label="用户列表" name="1">
        <Table stripe :columns="columns" :data="dataList">
          <template slot-scope="{ row, index }" slot="action">
            <Button
              type="primary"
              size="small"
              class="mr5"
              @click="editUser(row)"
              >编辑</Button
            >
            <Button type="error" size="small" @click="deleteUser(row)"
            >删除</Button
            >
<!--            <i-switch
              size="large"
              v-model="row.login_flag"
              true-value="1"
              false-value="0"
              @on-change="changeLoginFlag(row)"
            >
              <span slot="open">允许</span>
              <span slot="close">禁止</span>
            </i-switch>-->
          </template>
        </Table>
        <Page
          class="page_style"
          :total="param.totalRecord"
          :current="param.pageNo"
          :page-size="param.pageSize"
          @on-change="changePageNo"
          show-total
          show-sizer
          @on-page-size-change="size"
        />
      </TabPane>
      <TabPane :label="what === 'add' ? '添加用户' : '修改用户'" name="2">
        <Form
          ref="formValidate"
          :model="formData"
          :label-width="120"
          style="margin-left: 200px; width: 30%"
        >
          <FormItem
            label="用户姓名："
            prop="name"
            :rules="[{ required: true, message: '必填', trigger: 'blur' }]"
          >
            <Input v-model="formData.name" placeholder="请添加用户姓名"></Input>
          </FormItem>
          <FormItem
            label="身份证号码："
            prop="cardno"
            :rules="[{ required: true, message: '必填', trigger: 'blur' }]"
          >
            <Input
              v-model="formData.cardno"
              placeholder="请添加身份证号码"
            ></Input>
          </FormItem>
          <FormItem
            label="手机号："
            prop="phone"
            :rules="[{ required: true, message: '必填', trigger: 'blur' },
               { validator: checkNum, trigger: 'blur' }
            ]"
          >
            <Input v-model="formData.phone" placeholder="请添加手机号"></Input>
          </FormItem>
          <FormItem label="用户备注：" prop="remarks">
            <Input
              v-model="formData.remarks"
              placeholder="请添加用户备注"
            ></Input>
          </FormItem>
          <FormItem>
            <div class="flex-div">
              <Button type="primary" @click="save">保存</Button>
            </div>
          </FormItem>
        </Form>
      </TabPane>
    </Tabs>
  </div>
</template>
<script>
import {
  updateUser,
  insertGridUser,
  findGridUserList,
  updateGridUser,
  updateLoginFlagByUserId
} from '@//api/contradiction.js'
import { testid } from '@/api/common.js'
export default {
  name: 'gridUserManager',
  data () {
    return {
      formData: {},
      columns: [
        { title: '序号', type: 'index', align: 'center' },
        { title: '用户姓名', key: 'name', align: 'center' },
        { title: '手机号', key: 'phone', align: 'center' },
        {
          title: '身份证号',
          key: 'cardno',
          align: 'center',
          render: (h, params) => {
            const idCard = params.row.cardno
            if (idCard) {
              return h('span', this.maskIdCard(idCard))
            }
            return h('span', '')
          }
        },
        { title: '用户备注', key: 'remarks', align: 'center' },
        { title: '操作', slot: 'action', align: 'center' }
      ],
      dataList: [],
      dictList: [],
      tabValue: '1',
      params: this.$route.params,
      formData1: {},
      officeList: [],
      officeDict: [
        { label: '综治中心', value: '1' },
        { label: '单位', value: '2' }
      ],
      what: 'add',
      param: {
        pageNo: 1,
        pageSize: 10,
        totalRecord: 0
      }
    }
  },
  mounted () {
    this.getUserList()
    if (this.params) {
      this.formData.id = this.params.id
    }
  },
  methods: {
    maskIdCard (idCard) {
      if (idCard.length === 18) {
        return idCard.slice(0, 6) + '********' + idCard.slice(14)
      }
      return idCard // 如果不是18位，直接返回原值
    },
    checkNum (rule, value, callback) {
      if (!value) {
        callback(new Error('必填'))
      } else if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        callback(new Error('格式不正确'))
      } else {
        callback()
      }
    },
    changeLoginFlag (row) {
      updateLoginFlagByUserId({ id: row.id, login_flag: row.login_flag }).then(
        (res) => {
          if (res.data.errcode === 0) {
            this.$Message.success('操作成功')
            return
          }
          this.$Message.error(res.data.errmsg)
        }
      )
    },
    getUserList (params) {
      findGridUserList(params).then((res) => {
        if (res.data.errcode === 0) {
          this.dataList = res.data.data.results
          this.param.totalRecord = res.data.data.totalRecord
          return
        }
        this.$Message.error(res.data.errmsg)
      })
    },
    size (pageSize) {
      this.param.pageSize = pageSize
      this.changePageNo()
    },
    changePageNo (pageNo) {
      this.param.pageNo = pageNo
      this.getUserList(this.param)
    },
    save () {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          if (testid(this.formData.cardno)) {
            let url = this.what === 'add' ? insertGridUser : updateGridUser
            url(this.formData).then((res) => {
              if (res.data.errcode === 0) {
                this.$Message.success('操作成功')
                this.goToFirstTab()
                return
              }
              this.$Message.error(res.data.errmsg)
            })
          } else {
            this.$Message.error('身份证校验不合规')
          }
        } else {
          console.log('表单校验失败')
          return false
        }
      })
    },
    goToFirstTab () {
      this.$refs.tabs.activeKey = '1' // 假设Tabs组件的ref设置为tabs
      this.getUserList()
    },
    editUser (item) {
      this.$refs.tabs.activeKey = '2'
      this.what = 'edit'
      this.formData = JSON.parse(JSON.stringify(item))
    },
    deleteUser (item) {
      if (confirm('确定删除该用户吗')) {
        updateUser({ id: item.id, del_flag: '1' }).then((res) => {
          if (res.data.errcode === 0) {
            this.$Message.success('删除成功')
            this.getUserList()
            return
          }
          this.$Message.error(res.data.errmsg)
        })
      }
    },
    changeTab (name) {
      this.what = 'add'
      if (name === '2' && this.what === 'add') {
        this.formData = {}
      }
    }
  }
}
</script>
<style scoped lang="less">
.role-div {
  height:100%;
}
.flex-div {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.mr5 {
  margin-right: 5px;
}
.page_style {
  margin-top: 10px;
  text-align: right;
}
</style>
