<template>
  <div style="height: 100%; overflow: hidden">
    <div class="group-header">
      <a-button class="group-add" @click="showModal">
        <img class="icon-add" src="@/assets/images/global/add.png" alt="" />
        <span style="margin-left: 10px"> Add Contact Group </span>
      </a-button>
    </div>
    <div class="group-content">
      <a-spin :spinning="spinning">
        <a-collapse :activeKey="activeKey" :bordered="false">
          <a-collapse-panel :key="item.id" :style="customStyle" v-for="item in contactGroups">
            <template slot="header">
              {{ item.name }}
              <span class="header-sub"
                >Create Date: {{ item.createTime }} , Number of people: {{ item.personNumber }}</span
              >
            </template>
            <template slot="extra">
              <a-button class="actions" shape="circle" @click.stop="editGroup(item.id)">
                <img class="icon-edit" src="@/assets/images/abnormalAlarm/edit.png" alt="" />
              </a-button>
              <a-button class="actions" style="margin-right: 15px" shape="circle" @click.stop="deleteGroup(item.id)">
                <img class="icon-delete" src="@/assets/images/abnormalAlarm/delete.png" alt="" />
              </a-button>
            </template>
            <custom-table
              size="middle"
              rowKey="id"
              :columns="columns"
              :list="item.users"
              :pagination="false"
              :canSelect="false"
              :scroll="{ y: 200 }"
            >
              <template slot="name" slot-scope="{ text }">
                <img src="@/assets/images/abnormalAlarm/user.png" alt="" /><span
                  style="margin-left: 8px; padding-top: 2px"
                  >{{ text }}</span
                >
              </template>
              <template slot="role" slot-scope="{ record }">
                <span v-for="(role, index) in record.roles" :key="role.id"
                  >{{ role.roleName }}<i v-if="index != record.roles.length - 1">,</i></span
                >
              </template>

              <template slot="action" slot-scope="{ record }">
                <a-button
                  class="actions"
                  style="margin-right: 15px"
                  shape="circle"
                  @click="deleteUser(item.id, record.id)"
                >
                  <img class="icon-delete" src="@/assets/images/abnormalAlarm/delete.png" alt="" />
                </a-button>
              </template>
            </custom-table>
          </a-collapse-panel>
        </a-collapse>
      </a-spin>
      <a-pagination
        size="small"
        v-model="page.currentPage"
        :pageSize="page.pageSize"
        :page-size-options="page.pageSizeOptions"
        show-size-changer
        show-quick-jumper
        :total="page.total"
        :show-total="
          (total, range) => `Total ${total} items　Page ${page.currentPage} / ${Math.ceil(total / page.pageSize)}`
        "
        show-less-items
        @change="handlePageChange"
        @showSizeChange="handleSizeChange"
      />
    </div>

    <a-modal
      :title="isAdd ? 'Add Contact Group' : 'Edit Contact Group'"
      :width="845"
      :maskClosable="false"
      v-model="visible"
      @ok="handleOk"
      destroy-on-close
    >
      <!-- <a-spin :spinning="false"> -->
      <div class="group-assign">
        <a-transfer
          :dataSource="userList"
          :target-keys="targetKeys"
          :render="(item) => item.title"
          :operations="['Assign', 'Remove']"
          :titles="['All Users', 'Contact Group']"
          @change="handleChange"
          @search="handleSearch"
        >
        </a-transfer>
        <!-- 穿梭框右上方搜索 -->
        <div class="group-name">
          <!-- <label>Group Name</label>
              <a-input :value="groupName" placeholder="Basic usage" @change="setGroupName" /> -->
          <a-form :form="form" :label-col="{ span: 9 }" :wrapper-col="{ span: 15 }">
            <a-form-item label="Group Name">
              <a-input
                v-decorator="['name', { rules: [{ required: true, message: 'The group name is mandatory' }] }]"
              />
            </a-form-item>
          </a-form>
        </div>
        <!-- 穿梭框右上方搜索结束 -->
      </div>
      <!-- </a-spin> -->
      <template slot="footer">
        <slot name="custom-footer"></slot>
        <a-space class="operators" :size="20">
          <a-button type="success" @click="handleOk">Save</a-button>
          <a-button type="warn" @click="onCancel">Cancel</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { getAction, postAction, httpAction, deleteAction } from '@/api/manage'
const columns = [
  {
    title: 'NAME',
    align: 'left',
    dataIndex: 'username',
    scopedSlots: {
      customRender: 'name',
    },
  },
  {
    title: 'ROLE',
    align: 'left',
    dataIndex: 'roles',
    scopedSlots: {
      customRender: 'role',
    },
  },
  {
    title: 'Phone',
    align: 'left',
    dataIndex: 'telephone',
  },
  {
    title: 'E-MAIL',
    align: 'left',
    dataIndex: 'email',
  },
  {
    title: '',
    align: 'right',
    width: 80,
    scopedSlots: {
      customRender: 'action',
    },
  },
]
export default {
  data() {
    return {
      activeKey: '',
      spinning: false,
      page: {
        currentPage: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        total: 0,
      },
      contactGroups: [],
      isAdd: true,
      userList: [],
      groupList: [],
      columns,
      visible: false,
      customStyle: 'background: #02282b;;margin-bottom: 20px;border: solid 1px #416f7f;overflow: hidden',
      targetKeys: [],
      groupName: '',
      currGroupId: '',
      form: this.$form.createForm(this),
    }
  },
  mounted() {
    this.getAlarmGroup()
    this.getAllUser()
  },
  methods: {
    handlePageChange(page, pageSize) {
      this.page.currentPage = page
      this.page.pageSize = pageSize
      this.getAlarmGroup()
    },
    handleSizeChange(current, size) {
      this.page.currentPage = current
      this.page.pageSize = size
      this.getAlarmGroup()
    },
    getAlarmGroup() {
      this.spinning = true
      let params = {
        pageNo: this.page.currentPage,
        pageSize: this.page.pageSize,
      }
      getAction('/alarmContactGroup/findPage', params).then((res) => {
        this.spinning = false
        if (res.success) {
          this.contactGroups = res.result.records
          this.activeKey = this.contactGroups[0].id
          this.page.total = res.result.total
        } else {
          this.$message.warning('This operation fails. Contact your system administrator')
        }
      })
    },
    editGroup(id) {
      getAction('/alarmContactGroup/findInfo', { id }).then((res) => {
        if (res.success) {
          this.visible = true
          this.isAdd = false
          // this.groupName = res.result.name
          this.$nextTick(() => {
            this.form.setFieldsValue({
              name: res.result.name,
            })
          })
          this.targetKeys = res.result.userIds
          this.currGroupId = res.result.id
        } else {
          this.$message.warning('This operation fails. Contact your system administrator')
        }
      })
    },
    getAllUser() {
      getAction('sys/user/list').then((res) => {
        if (res.success) {
          this.userList = res.result.records.map((item) => {
            return {
              key: item.id,
              title: item.username,
            }
          })
        } else {
          this.$message.warning('This operation fails. Contact your system administrator')
        }
      })
    },
    handleChange(targetKeys, direction, moveKeys) {
      this.targetKeys = targetKeys
    },
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.targetKeys.length > 0) {
            if (this.isAdd) {
              this.createContactGroup(values.name)
            } else {
              this.updateContactGroup(values.name)
            }
          } else {
            this.$message.warning('Please select User')
          }
        }
      })
    },
    onCancel() {
      this.visible = false
    },
    updateContactGroup(name) {
      let params = {
        name,
        description: '',
        userIds: this.targetKeys,
        id: this.currGroupId,
      }
      httpAction('/alarmContactGroup/update', params, 'put').then((res) => {
        if (res.success) {
          this.visible = false
          this.$message.success('success')
          this.getAlarmGroup()
        } else {
          this.$message.warning('This operation fails. Contact your system administrator')
        }
      })
    },
    createContactGroup(name) {
      let params = {
        name,
        description: '',
        userIds: this.targetKeys,
      }
      postAction('/alarmContactGroup/create', params).then((res) => {
        if (res.success) {
          this.visible = false
          this.$message.success('success')
          this.getAlarmGroup()
        } else {
          this.$message.warning('This operation fails. Contact your system administrator')
        }
      })
    },
    deleteGroup(id) {
      let _this = this
      this.$confirm({
        title: 'Are you sure to delete this item?',
        onOk() {
          deleteAction('/alarmContactGroup/deleteById', { id }).then((res) => {
            if (res.success) {
              _this.$message.success('success')
              _this.getAlarmGroup()
            } else {
              _this.$message.warning('This operation fails. Contact your system administrator')
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'test',
      })
    },
    deleteUser(id, userId) {
      let _this = this
      this.$confirm({
        title: 'Are you sure to delete this item?',
        onOk() {
          deleteAction('/alarmContactGroup/deleteUserById', { id, userId }).then((res) => {
            if (res.success) {
              _this.$message.success('success')
              _this.getAlarmGroup()
            } else {
              _this.$message.warning('This operation fails. Contact your system administrator')
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    handleSearch(dir, value) {
      console.log('search:', dir, value)
    },
    showModal() {
      this.targetKeys = []
      this.groupName = ''
      this.form.setFieldsValue({
        name: '',
      })
      this.visible = true
    },
  },
}
</script>

<style lang="less" scoped>
.operators {
  width: 100%;
  justify-content: center;
  .ant-btn {
    width: 92px;
  }
}
.group-header {
  height: 50px;
  border-top: 1px solid rgba(13, 235, 201, 0.3);
  border-bottom: 1px solid rgba(13, 235, 201, 0.3);
  margin: 0 0 15px 20px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  background: rgba(12, 235, 201, 0.05);
  .group-add {
    background-color: #1397a3;
    font-family: ArialMT;
    color: #ffffff;
    border: none;
    box-shadow: 0px 1px 1px 0px #000000;
  }
}
.group-content {
  height: calc(100% - 65px);
  margin-left: 20px;
  position: relative;
  .ant-spin-nested-loading {
    width: 100%;
    height: calc(100% - 30px);
    overflow: auto;
  }
  .header-sub {
    margin-left: 20px;
    font-family: MicrosoftYaHei;
    font-size: 16px;
    color: #ade6ee;
  }
  // .ant-collapse{
  //   height: calc(100% - 30px);
  //   overflow: auto;
  // }
  .actions {
    background: none;
    border: none;
    margin-left: 10px;
  }
  .split-float:last-child {
    display: none;
  }
  .ant-pagination {
    position: absolute;
    left: 50%;
    bottom: 0;
    transform: translateX(-50%);
  }
}
::v-deep {
  .ant-collapse-header {
    height: 50px;
    background-color: rgba(13, 109, 118, 0.2);
    font-family: ArialMT;
    color: #fff !important;
    line-height: 50px !important;
    padding-left: 35px !important;
    font-size: 18px;
  }
  .ant-collapse-content-box {
    padding: 15px !important;
  }
  .ant-modal-title {
    letter-spacing: 1px;
  }
  .ant-form-item-label > label {
    font-family: ArialMT;
    color: #5b9cba;
  }
}
.group-assign {
  position: relative;
  width: 690px;
  margin: 0 auto;
  .ant-transfer {
    margin-bottom: 10px;
    ::v-deep {
      .ant-transfer-list {
        width: 291px;
        height: 411px;
        padding-top: 0;
        &-header {
          height: 37px;
          &-selected {
            span:first-child {
              display: none;
            }
          }
          &-title {
            left: 16px;
          }
        }
        &-content {
          &-item {
            &:hover {
              background-color: transparent;
            }
          }
        }

        &:last-child {
          height: 345px;
          position: relative;
          top: 35px;
        }
      }

      .ant-transfer-operation {
        .ant-btn {
          width: 92px;
          height: 26px;
          padding: 0;
          .anticon {
            display: none;
          }
          span {
            margin-left: 0;
          }
          &:first-child {
            margin-bottom: 52px;
            &::after {
              display: inline-block;
              margin-left: 13px;
              content: '';
              width: 18px;
              height: 10px;
              background: url(~@/assets/images/system/transfer-right.png) no-repeat;
              background-size: contain;
            }
          }
          &:nth-child(2) {
            &::before {
              display: inline-block;
              margin-right: 6px;
              content: '';
              width: 18px;
              height: 10px;
              background: url(~@/assets/images/system/transfer-left.png) no-repeat;
              background-size: contain;
              position: static;
              opacity: initial;
            }
          }
        }
      }
      .ant-transfer-list-header {
        position: relative;
        .ant-checkbox-wrapper {
          position: absolute;
          right: 10px;
        }
      }
      .ant-transfer-list-content-item {
        position: relative;
        &::before {
          content: '';
          display: inline-block;
          width: 16px;
          height: 16px;
          background: url(~@/assets/images/abnormalAlarm/user.png) no-repeat;
          background-size: contain;
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
        }
        .ant-checkbox-wrapper {
          position: absolute;
          right: 10px;
        }
      }
      .ant-transfer-list-content-item-text {
        padding-left: 22px;
      }
    }
  }
  .group-name {
    position: absolute;
    top: 0;
    right: 0;
    width: 300px;
    display: flex;
    align-items: center;
    label {
      color: #5b9cba;
      font-size: 16px;
      flex-shrink: 0;
      margin-right: 10px;
      user-select: none;
    }
  }
  .transfer-left-item {
    position: relative;
    height: 32px;
    line-height: 32px;
    font-size: 14px;
    &-checkBox {
      float: right;
    }
  }
}
</style>