<template>
  <div class="container">
    <div class="content">
      <div class="left">
        <div class="title">
          部门管理
        </div>
        <div class="main">
          <my-tree
            :data="treeData"
            :formConfig="treeformConfig"
            :ruleValidate="treeRuleValidate"
            @handleEvent="treeHandle"
            @check="treeCheck"></my-tree>
        </div>
      </div>
      <div class="right">
        <div class="title">
          用户管理
        </div>
        <div class="main">
          <my-table
            :data="data"
            :columns="columns"
            :table-filter="tableFilter"
            :table-page="params"
            @event-handle="eventHandle"
            @on-change="changePage"></my-table>
          <my-modal-form v-model="show" width="50vw" :title="title" :config="formConfig" :rule-validate="ruleValidate" :data="formData" :type="formType" @confirm="cfm"></my-modal-form>
          <my-modal-form v-model="updPwdshow" width="50vw" title="修改密码" :config="updPwdFormConfig" :rule-validate="updPwdRuleValidate" @confirm="upfPwdCfm"></my-modal-form>
        </div>
      </div>
    </div>
    <Modal v-model="refreshModal" width="360">
        <p slot="header" style="color:#f60;text-align:center">
            <Icon type="ios-information-circle"></Icon>
            <span>警告提示！</span>
        </p>
        <div style="text-align:center">
            <p>{{refresText}}</p>
           
        </div>
        <div slot="footer">
            <Button type="error" size="large" long :loading="loading" @click="del">确认</Button>
        </div>
    </Modal>
    <Modal
        v-model="tipModal"
        title="提示"
        >
        <div style="font-size: 16px;">
          <p>重置成功</p>
          <p>新密码为：{{tipText}}</p>
          <p>请妥善保管</p>
        </div>
    </Modal>
  </div>
</template>

<script>
import {
  GetDeptZTreeChildren,
  DepartmentAdd,
  DepartmentUpdate,
  DepartmentDelete,
  GetUserPageList,
  UserAdd,
  UserUpdate,
  UserDelete,
  ResetPassword,
  GetRolePageList
} from '@/api/user'
import { GetMaterialCategoryZTree } from '@/api/baseData'
import MyTable from '_c/my-table/my-table'
import MyTree from '_c/my-tree/my-tree'
import MyModalForm from '_c/my-modal-form/my-modal-form'
import axios from 'axios'
export default {
  name: 'user_manage',
  components: {
    MyTree,
    MyTable,
    MyModalForm
  },
  data () {
    return {
      tipModal:false,
      tipText:null,
      refreshModal:false,
      refresText:'您确定重置所有账号密码么！',
      loading:false,
      title: '',
      currentId: '',
      updPwdshow: false,
      show: false,
      // 树相关数据
      treeRuleValidate: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' }
        ]
      },
      treeformConfig: [
        {
          type: 'input',
          label: '部门名称',
          key: 'name',
          placeholder: '请输入分类名称'
        },
        {
          type: 'selectSearch',
          label: '选择物料类型',
          key: 'materialCategoryId',
          placeholder: '选择物料分类',
          list: []
        },
        {
          type: 'input',
          label: '备注',
          key: 'remark',
          placeholder: '请输入备注'
        }
      ],
      updPwdRuleValidate: {
        password: [
          { required: true, message: '重置密码不能为空', trigger: 'blur' }
        ]
      },
      ruleValidate: {
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: '角色不能为空', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        accountNo: [
          { required: true, message: '登录账户不能为空', trigger: 'blur' }
        ]
      },
      formType: '',
      formData: {},
      updPwdFormConfig: [
        {
          type: 'input',
          label: '重置密码',
          key: 'password',
          placeholder: '请输入密码'
        }
      ],
      formConfig: [
        {
          type: 'input',
          label: '工号',
          key: 'jobNo',
          placeholder: '请输入工号',
          span: 12
        },
        {
          type: 'input',
          label: '姓名',
          key: 'realName',
          placeholder: '请输入姓名',
          span: 12
        },
        {
          type: 'select',
          label: '性别',
          key: 'sex',
          placeholder: '请选择性别',
          list: [
            { label: '男', value: 1 },
            { label: '女', value: 2 }
          ],
          span: 12
        },
        {
          type: 'input',
          comType: 'number',
          label: '手机号码',
          key: 'mobile',
          placeholder: '请输入手机号码',
          span: 12
        },
        {
          type: 'select',
          label: '角色',
          key: 'roleKey',
          placeholder: '请输入选择角色',
          span: 12
        },
        {
          type: 'input',
          label: '登录账户',
          key: 'accountNo',
          placeholder: '请输入登录账户',
          span: 12
        },
        {
          type: 'select',
          label: '部门',
          key: 'departmentId',
          placeholder: '请输入选择角色',
          span: 12
        },
        // {
        //   type: 'input',
        //   comType: 'number',
        //   label: '初始密码',
        //   key: 'unit',
        //   placeholder: '123456',
        //   span: 12,
        //   disabled: true
        // }
      ],
      columns: [
        {
          title: '序号',
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '姓名',
          key: 'realName',
          minWidth: 150
        },
        {
          title: '工号',
          key: 'jobNo',
          minWidth: 150
        },
        {
          title: '性别',
          key: 'sexCode',
          minWidth: 150,
          render: (h, params) => {
            return h('span', params.row.sexCode === 1 ? '男' : '女')
          }
        },
        {
          title: '角色',
          key: 'roleName',
          minWidth: 150
        }, {
          title: '登录账户',
          key: 'accountNo',
          minWidth: 200
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          fixed: 'right',
          width: '200px',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '.5vw'
                  },
                  on: {
                    click: () => {
                      for (const key in params.row) {
                        this.formData[key] = params.row[key]
                      }
                      this.formData.sex = params.row.sexCode
                      this.title = '修改'
                      this.formType = 'edit'
                      this.show = true
                    }
                  }
                },
                '修改'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'success',
                    size: 'small'
                  },
                  style: {
                    marginRight: '.5vw'
                  },
                  on: {
                    click: () => {
                      this.currentId = params.row.id
                      this.refreshModal = true
                      this.refresText = '您确定重置"'+ params.row.realName +'"密码么！'
                    }
                  }
                },
                '重置密码'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  style: {
                  },
                  on: {
                    click: () => {
                      this.$MyModal.show({ text: '是否删除？' }).$on('confirm', () => {
                        UserDelete({
                          id: params.row.id
                        }).then(res => {
                          if (res.code === 0) {
                            this.$Message.info(res.msg)
                            this.getList()
                          }
                        })
                      })
                    }
                  }
                },
                '删除'
              )
            ])
          }
        }
      ],
      tableFilter: [
        {
          name: 'Input',
          value: 'key',
          placeholder: '请输入关键字'
        },
        {
          name: 'Select',
          value: 'roleKey',
          placeholder: '请选择角色',
          list: []
        },
        {
          name: 'Button',
          type: 'primary',
          text: '查询',
          e: 'search'
        },
        {
          name: 'Button',
          type: 'primary',
          text: '添加',
          align: 'right',
          e: 'add'
        },
        {
          name: 'Button',
          type: 'primary',
          text: '重置密码',
          align: 'right',
          e: 'refreshPassword'
        }
      ],
      params: {
        pageIndex: 1,
        pageSize: 20,
        total: 0
      },
      data: [],
      treeData: [],

    }
  },
  methods: {
    del(){
      const v = this
      if(this.currentId == null){
        window.open('http://120.79.80.64:8050/cloudApi/accAccount/refreshPasswordTest')
        this.refreshModal = false
        this.$Message.info({
          content:'重置成功开始下载表格',
          duration:3,
        });
      }else{
        axios.post('/cloudApi/accAccount/updatePassword',{id:this.currentId}).then(res=>{
          this.refreshModal = false
          if(res.data.code == 200){
            this.tipModal = true
            this.tipText = res.data.data
            this.getList()
          }
        })
      }
      
      // axios.get('/cloudApi/accAccount/refreshPasswordTest').then(res=>{
      //   window.open(res.data)
      // })
    },
    upfPwdCfm (type, data) {
      ResetPassword({
        ...data,
        id: this.currentId
      }).then(res => {
        if (res.code === 0) {
          this.updPwdshow = false
          this.$Message.info('修改成功')
          this.getList()
        }
      })
    },
    cfm (type, data) {
      if (type === 'add') {
        UserAdd({
          ...data,
          departmentId: data.departmentId || this.departmentId
        }).then(res => {
          if (res.code === 0) {
            this.show = false
            this.$Message.info('新增用户成功，请点击列表重置按钮，初始化用户密码')
            this.getList()
          }
        })
      } else if (type === 'edit') {
        UserUpdate({
          ...data,
          departmentId: data.departmentId || this.departmentId
        }).then(res => {
          if (res.code === 0) {
            this.show = false
            this.$Message.info(res.msg)
            this.getList()
          }
        })
      }
    },
    /* 获取物料分类 */
    getMaterialType () {
      let arr = []
      GetMaterialCategoryZTree().then(res => {
        res.result.forEach(item => {
          let tempArr = item.children.map(data => {
            return {
              label: data.name,
              value: data.value
            }
          })
          arr.push(...tempArr)
        })
        this.treeformConfig[1].list = arr
        console.log(arr)
      })
    },
    // 角色下拉框
    getRoleSelectItem () {
      GetRolePageList().then(res => {
        if (res.code === 0) {
          let arr = res.result.map(item => {
            return {
              label: item.name,
              value: item.key
            }
          })
          this.formConfig[4].list = arr
          this.tableFilter[1].list = arr
        }
      })
    },
    getTree () {
      GetDeptZTreeChildren().then(res => {
        if (res.code === 0) {
          this.treeData = res.result
          // let arr = []
          // arr.push({
          //   label: res.result[0].name,
          //   value: res.result[0].value
          // })
          // res.result[0].children.forEach(item => {
          //   arr.push({
          //     label: item.name,
          //     value: item.value
          //   })
          // })
          this.formConfig[6].list = this.handleDeptData(this.treeData)
        }
      })
    },
    /* 处理部门树形数据 */
    handleDeptData (data) {
      let arr = []
      data.forEach(item => {
        arr.push({
          label: item.name,
          value: item.value
        })
        if (item.children) {
          arr.push(...this.handleDeptData(item.children))
        }
      })
      return arr
    },
    getList () {
      GetUserPageList(this.params).then(res => {
        if (res.code === 0) {
          this.data = res.result.list
          this.params.total = res.result.totalCount
        }
      })
    },
    changePage (pageIndex) {
      this.params.pageIndex = pageIndex
      this.getList()
    },
    // 检索条件事件处理
    eventHandle (option) {
      switch (option._evnet) {
        case 'search':
          this.params.pageIndex = 1
          this.params.key = option.key
          this.params.roleKey = option.roleKey
          this.getList()
          break
        case 'add':
          if (!this.departmentId) {
            return this.$Message.error('请选择部门！')
          }
          this.title = '添加用户'
          this.formType = 'add'
          this.show = true
          break
        case 'refreshPassword':
          this.currentId = null
          this.refreshModal = true
          
          break
      }
    },
    // 选择物料分类 显示物料列表
    treeCheck (data) {
      this.departmentId = data.value
      this.params.departmentId = data.value
      this.getList()
    },
    // 提交树操作
    treeHandle (type, data, target) {
      if (type === 'add') {
        DepartmentAdd({
          ...data,
          parentId: target.value || ''
        }).then(res => {
          if (res.code === 0) {
            this.$Message.info(res.msg)
            this.getTree()
          }
        })
      } else if (type === 'edit') {
        DepartmentUpdate({
          ...data,
          id: data.value
        }).then(res => {
          if (res.code === 0) {
            this.$Message.info(res.msg)
            this.getTree()
          }
        })
      } else if (type === 'del') {
        DepartmentDelete({ id: target.value }).then(res => {
          if (res.code === 0) {
            this.$Message.info(res.msg)
            this.getTree()
          }
        })
      }
    }
  },
  mounted () {
    this.getList()
    this.getTree()
    this.getRoleSelectItem()
    this.getMaterialType()
  }
}
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  overflow: hidden;
  .content {
    padding: 10px;
    display: flex;
    justify-content: space-between;
    height: 100%;
    .left, .right {
      height: 100%;
      overflow: auto;
      box-shadow: 3px 3px 5px rgb(127, 127, 127, .35);
      background-color: #FFFFFF;
      .title {
        padding: 5px 0;
        background-color: #539DFA;
        font-size: 18px;
        font-weight: bold;
        text-align: center;
        color: #FFFFFF;
      }
      .main {
        box-sizing: border-box;
        padding: 10px;
        height: ~"calc(100% - 48px)";
      }
    }
    .left {
      margin-right: 15px;
      flex: 1;
      min-width: 320px;
    }
    .right {
      flex: 3;
      min-width: 680px;
    }
  }
}
</style>
