<template>
  <div>
    <el-row>
      <el-col :span="4">
        <el-button @click="addUser()" type="success" size="mini" style="margin-left:20px;"><i
            class="el-icon-plus"></i> 新增
        </el-button>
      </el-col>
      <el-col :span="20">
        <div style="text-align: right;">
          <el-input style="width:200px;" size="mini" v-model="queryUserName" placeholder="用户名"></el-input>
          <el-cascader
              v-model="queryUserType"
              :options="userTypeOptions"
              placeholder="用户类别"
              style="margin-left:20px;width:150px;"
              size="mini"
              :show-all-levels="false"
              :clearable="true"></el-cascader>
          <el-cascader
              v-model="queryUserFlag"
              :options="userFlagOptions"
              placeholder="启用状态"
              style="margin-left:20px;width:150px;"
              size="mini"
              :show-all-levels="false"
              :clearable="true"></el-cascader>
          <el-button @click="querySocialUser" type="primary" size="mini"
                     style="margin-left:10px;"><i class="el-icon-search"></i> 查询
          </el-button>
          <el-button @click="refreshQuery" type="info" size="mini"
                     style="margin-left:10px;"><i class="el-icon-refresh"></i> 重置
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <mytable :metaData="metadataOfUser" :tableData="tableDataOfUser" :isLoading="isLoading"
                 @selection-change="handleSelectionChangeOfUser">
          <template #default="{ index }">
            <el-button-group>
              <el-button size="small" icon="fa fa-edit"
                         @click="viewRuleOfUser(index, tableDataOfUser)"></el-button>
              <el-button size="small" icon="fa fa-trash" @click="deleteOne(tableDataOfUser[index].id)"></el-button>
            </el-button-group>
          </template>
        </mytable>
        <el-pagination background layout="total, prev, pager, next, jumper" :total="total" :current-page="pageIndex"
                       @current-change="onPageChange" style="padding: 15px"></el-pagination>
      </el-col>
    </el-row>

    <el-dialog
        title="添加用户"
        :visible.sync="dialogVisibleOfUser"
        width="35%"
        center>
      <div class="dialogForm">
        <el-form :model="formDataOfUser" :label-width="formLabelWidth" class="demo-form">
          <el-divider>基础属性</el-divider>
          <el-form-item label="用户名">
            <el-input v-model="formDataOfUser.userName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户UID">
            <el-input v-model="formDataOfUser.userUid" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="关键字">
            <el-input v-model="formDataOfUser.keywords" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户类型">
            <el-cascader
                v-model="formDataOfUser.userType"
                :options="userTypeOptions"></el-cascader>
          </el-form-item>
          <el-form-item label="是否启用">
            <el-cascader
                v-model="formDataOfUser.userFlag"
                :options="userFlagOptions"></el-cascader>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
                v-model="formDataOfUser.memo"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 5}"
                placeholder="请输入内容"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
                  <el-button size="small" type="success" @click="saveUser">保存</el-button>
                  <el-button style="margin-left: 10px;" size="small" type="primary"
                             @click="cancelSaveUser">取消</el-button>
              </span>
    </el-dialog>
  </div>
</template>
<script>
import Vue from 'vue'
import {
  Select,
  Option,
  Input,
  Row,
  Col,
  Button,
  Dialog,
  Form,
  FormItem,
  Message,
  Divider,
  Cascader,
  Dropdown,
  DropdownMenu,
  DropdownItem, MessageBox
} from 'element-ui'
import myTable from '../components/CustomTable'
import metaDictApi from '../../js/api/metaDictApi'
import socialApi from '../../js/api/targetSocialApi'

Vue.use(Select)
Vue.use(Option)
Vue.use(Input)
Vue.use(Row)
Vue.use(Col)
Vue.use(Button)
Vue.use(Dialog)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Divider)
Vue.use(Cascader)
Vue.use(Dropdown)
Vue.use(DropdownMenu)
Vue.use(DropdownItem)

export default {
  name: 'SocialUserManage',
  inject: ['reload'],
  components: {
    'mytable': myTable
  },
  data() {
    return {
      isLoading: false,
      formLabelWidth: '100px',
      total: 0,
      pageIndex: 0,
      //新增字段
      queryUserName: '',
      queryUserType: '',
      queryUserFlag: '',
      userTypeOptions: [],
      userFlagOptions: [{label: "启用", value: "0"}, {label: "不启用", value: "1"}],
      multipleSelectionOfUser: [],
      tableDataOfUser: [],
      formDataOfUser: {
        userName: '',
        userUid: '',
        userType: '',
        userFlag: '',
        keywords: '',
        memo: ''
      },
      dialogVisibleOfUser: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    }
  },
  computed: {
    metadataOfUser: function () {
      let temp = [];
      this.$store.state.metadata.metadata.forEach(element => {
        if (element.tableName === 'target_social') {
          let tempElement = {...element};
          tempElement.minWidth = tempElement.columnWidth + "%";
          tempElement.columnWidth = 0;
          temp.push(element);
        }
      });
      return temp;
    }
  },
  methods: {
    addUser() {
      this.formDataOfUser = {
        userName: '',
        userUid: '',
        userType: '',
        userFlag: '',
        keywords: ''
      };
      this.dialogVisibleOfUser = true;
    },
    deleteOne(id) {
      MessageBox.confirm("是否删除？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        socialApi.delete({id: id}, response => {
          if (response.data.code === 200) {
            Message({
              message: '删除成功！',
              type: 'success'
            })
            this.querySocialUser();
          }
        })
      })
          .catch(() => {
          })
    },
    setQueryParams() {
      let params = {}
      if (this.queryUserName.length > 0) {
        params['userName'] = this.queryUserName
      }
      if (this.queryUserType.length > 0) {
        params['userType'] = this.queryUserType[0]
      }
      if (this.queryUserFlag.length > 0) {
        params['userFlag'] = this.queryUserFlag[0]
      }
      return params
    },
    querySocialUserPageable(page, size) {
      this.isLoading = true;
      let queryParams = this.setQueryParams()
      socialApi.queryPageable(page, size, queryParams, (response) => {
        if (response.data.code === 200) {
          this.tableDataOfUser = response.data.content;
          this.total = parseInt(response.data.message);
          this.isLoading = false;
        } else {
          this.isLoading = false;
        }
      })
    },
    handleSelectionChangeOfUser(val) {
      this.multipleSelectionOfUser = val;
    },
    viewRuleOfUser(index, tableDataOfUser) {
      this.formDataOfUser = {...tableDataOfUser[Number(index)]};
      this.dialogVisibleOfUser = true;
    },
    onPageChange(index) {
      this.pageIndex = index
      this.querySocialUserPageable(this.pageIndex - 1, 10);
    },
    saveUser() {
      let tempData = {...this.formDataOfUser}
      //处理用户类型
      tempData.userType = tempData.userType.constructor === Array ? tempData.userType[tempData.userType.length - 1] : tempData.userType
      tempData.userFlag = tempData.userFlag.constructor === Array ? tempData.userFlag[tempData.userFlag.length - 1] : tempData.userFlag
      socialApi.save(tempData, response => {
        if (response.data.code === 200) {
          this.querySocialUser()
          Message({
            message: "添加成功！",
            type: "success"
          });
          this.dialogVisibleOfUser = false;
        }
      })
    },
    cancelSaveUser() {
      this.dialogVisibleOfUser = false;
      this.formDataOfUser = {
        userName: '',
        userUid: '',
        userType: '',
        userFlag: '',
        keywords: ''
      }
    },
    querySocialUser() {
      this.pageIndex = 1;
      this.querySocialUserPageable(this.pageIndex - 1, 10);
    },
    refreshQuery() {
      this.queryUserName = ''
      this.queryUserType = '';
      this.queryUserFlag = '';
      this.pageIndex = 1;
      this.querySocialUserPageable(this.pageIndex - 1, 10);
    },
    buildDictTree(data, columnString) {
      let siteOptions = []
      let nodeList = []
      data.forEach(e => {
        if (e.columnName === columnString)
          nodeList.push({value: e.dictCode, label: e.dictValue, children: undefined, parentDictCode: e.parentDictCode});
      })
      nodeList.forEach(e1 => {
        if (e1.parentDictCode !== undefined) {
          nodeList.forEach(e2 => {
            if (e1.parentDictCode === e2.value) {
              if (e2.children === undefined) {
                e2.children = []
              }
              e2.children.push(e1);
            }
          })
        } else {
          siteOptions.push(e1);
        }
      })
      return siteOptions;
    }
  },
  mounted: function () {
    if (this.userTypeOptions.length === 0) {
      metaDictApi.queryByTableName('target_social', (response) => {
        if (response.data.code === 200) {
          this.userTypeOptions = this.buildDictTree(response.data.content, 'userType');
        }
      })
    }
    this.querySocialUser();
  }
}
</script>

<style scoped>
.searchBar {
  padding-bottom: 20px;
  border-bottom: solid 1px lightgrey;
}

.dialogForm {
  display: flex;
  justify-content: center;
}

.demo-form {
  width: 450px;
}

.demo-form .el-input, .el-cascader, .el-textarea {
  width: 300px;
}

.dialogForm, .el-pagination {
  display: flex;
  justify-content: center;
}
</style>