<template>
  <div>
    <a-form @submit="handleSubmit" :form="form" class="cust-detail-form">
      <header-tool-bar>
        <span class="cust-title" slot="title">
          <a-icon type="hdd" />角色管理明细
        </span>
        <a-button-group slot="extra">
          <a-button type="primary" htmlType="submit">保存</a-button>
          <a-button type="primary" @click="back" ghost>返回</a-button>
        </a-button-group>
      </header-tool-bar>
      <a-card title="基础数据" class="cust-normal-card">
        <a-row>
          <a-col :span="6">
            <a-form-item v-bind="formItemLayout" label="编号">
              <a-input
                v-decorator="[
                  'sysRole.code',
                  {
                    initialValue: sysRole.code,
                    rules: [{ required: true, message: '请输入编号' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item v-bind="formItemLayout" label="名称">
              <a-input
                v-decorator="[
                  'sysRole.name',
                  {
                    initialValue: sysRole.name,
                    rules: [{ required: true, message: '请输入名称' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item v-bind="formItemLayout" label="状态">
              <a-select
                :disabled="this.id == 1"
                v-decorator="[
                  'sysRole.isEnabled',
                  {
                    initialValue: sysRole.isEnabled,
                    rules: [{ required: true, message: '请选择状态' }]
                  }
                ]"
              >
                <a-select-option :key="1" :value="1" >启用 </a-select-option>
                <a-select-option :key="2" :value="0" >禁用 </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item v-bind="formmarkItemLayout" label="备注">
              <a-textarea
                :autoSize="{ minRows: 2, maxRows: 6 }"
                v-decorator="[
                  'sysRole.remark',
                  {
                    initialValue: sysRole.remark,
                    rules: [{ required: true, message: '请输入备注' }]
                  }
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <a-card title="业务操作" class="cust-normal-card">
        <a-table
          :columns="columns"
          :dataSource="itemList"
          size="middle"
          rowKey="id"
          :pagination="false"
          :defaultExpandAllRows="true"
          class="cust-card-table"
          :scroll="{ y: $store.getters.size[1] - 450 }"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: updateSelect,
            onSelect: rowSelect,
            onSelectAll: rowSelectAll
          }"
          bordered
        >
          <span slot="action" slot-scope="text, record">
            <a-checkbox
              v-for="item in record.sysBusinessOperateList"
              :key="item.id"
              :checked="item.selected"
              @change="onChange(item, record)"
              >{{ item.name }}</a-checkbox
            >
          </span>
        </a-table>
      </a-card>
    </a-form>
  </div>
</template>

<script>
import HeaderToolBar from '@/components/page/HeaderToolBar'
import { getDetail, save } from '@/api/system/sysRole'

let listPathName = 'sysRoleList'
const columns = [
  { title: '业务名称', width: 300, dataIndex: 'name' },
  {
    title: '操作',
    key: 'operation',
    dataIndex: 'sysBusinessOperateList',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'SysRoleDetail',
  components: { HeaderToolBar },
  data() {
    return {
      id: 0,
      checkedList: [],
      form: this.$form.createForm(this),
      sysRole: {},
      itemList: [],
      saveOperatedList: [],
      typeList: [],
      columns: columns,
      currentEditDate: {},
      selectedRowKeys: [],
      formItemLayout: {
        labelCol: {
          sm: { span: 8 }
        },
        wrapperCol: {
          sm: { span: 16 }
        }
      },
      formmarkItemLayout: {
        labelCol: {
          sm: { span: 2 }
        },
        wrapperCol: {
          sm: { span: 22 }
        }
      }
    }
  },
  activated() {
    this.form.resetFields()
    this.selectedRowKeys = []
    this.initData()
  },
  deactivated() {
    this.itemList = []
  },
  methods: {
    onChange(item, record) {
      item.selected = !item.selected
      if (item.selected == true) {
        if (
          record.sysBusinessOperateList.filter((opt) => opt.selected != true)
            .length == 0
        ) {
          this.selectedRowKeys.push(item.businessId)
        }
      } else {
        this.selectedRowKeys = this.selectedRowKeys.filter(
          (key) => key != record.id
        )
      }
    },
    initData() {
      this.id = this.$route.query.id || 0
      getDetail(this.id).then((resp) => {
        if (resp && resp.code == SYS_CONST.REQUEST.SUCCEED) {
          this.sysRole = resp.data.sysRole
          this.sysRole.isEnabled = this.sysRole.isEnabled ? 1 : 0
          this.itemList = []
          if (resp.data.sysBusinessTreeList) {
            this.itemList = resp.data.sysBusinessTreeList[0].children
          }
          this.checkChildren(this.itemList)
          this.checkSelectRow(this.itemList)
        }
      })
    },
    checkChildren(list) {
      list.map((m) => {
        if (m.children.length == 0) {
          m.children = null
        } else {
          this.checkChildren(m.children)
        }
      })
    },
    checkSelectRow(businessList) {
      let count = 0
      businessList.map((m) => {
        if (
          m.children == null &&
          m.sysBusinessOperateList.filter((opt) => opt.selected != true)
            .length == 0
        ) {
          this.selectedRowKeys.push(m.id)
          count++
        }
        if (m.children != null) {
          let checkedCount = this.checkSelectRow(m.children)
          if (checkedCount === m.children.length) {
            this.selectedRowKeys.push(m.id)
            count++
          }
        }
      })
      return count
    },
    handleSubmit(e) {
      e.preventDefault()
      this.getSelectedOperate()
      if (this.saveOperatedList.length == 0) {
        this.$notification.error({
          message: '系统提示',
          description: '请至少勾选一个业务操作',
          duration: 4
        })
        return
      }
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          let saveData = {
            sysRole: this.$valueCopy(this.sysRole, values.sysRole),
            saveOperatedList: this.saveOperatedList
          }
          save(saveData).then((resp) => {
            if (resp && resp.code == SYS_CONST.REQUEST.SUCCEED) {
              this.$notification.success({
                message: '系统提示',
                description: '保存成功',
                duration: 4
              })
              this.$router.push({
                name: listPathName,
                query: { isModify: this.id != 0 }
              })
            }
          })
        }
      })
    },
    updateSelect(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    rowSelect(record, selected) {
      let curList = this.getCurList(record.id, this.itemList)
      curList.map((m) => {
        if (m.id == record.id) {
          m.sysBusinessOperateList.map((o) => {
            o.selected = selected
          })
          if (m.children != null) {
            this.selectOperateByBusiness(m.children, selected)
          }
        }
      })
    },
    getCurList(curId, parantList) {
      let curList = []
      for (let i = 0; i < parantList.length; i++) {
        let item = parantList[i]
        if (item.id == curId) {
          curList = parantList
        } else if (item.children != null) {
          curList = this.getCurList(curId, item.children)
        }
        if (curList.length > 0) {
          break
        }
      }
      return curList
    },
    selectOperateByBusiness(businessList, selected) {
      businessList.map((m) => {
        if (selected) {
          this.selectedRowKeys.push(m.id)
        } else {
          this.selectedRowKeys = this.selectedRowKeys.filter((s) => s != m.id)
        }
        m.sysBusinessOperateList.map((o) => {
          o.selected = selected
        })
        if (m.children != null) {
          this.selectOperateByBusiness(m.children, selected)
        }
      })
    },
    rowSelectAll(selected) {
      this.selectOperateByBusiness(this.itemList, selected)
    },
    back() {
      this.$router.push({ name: listPathName })
    },
    modifyItem(type, item) {
      if (type == SYS_CONST.OPT_TYPE.ADD) {
        this.itemList.push(item)
      } else {
        this.$valueCopy(this.currentEditDate, item)
      }
    },
    getSelectedOperate() {
      this.saveOperatedList = []
      this.getSaveOperateByList(this.itemList)
    },
    getSaveOperateByList(businessList) {
      businessList.map((m) => {
        m.sysBusinessOperateList.map((o) => {
          if (o.selected == true) {
            this.saveOperatedList.push(o.id)
          }
        })
        if (m.children != null) {
          this.getSaveOperateByList(m.children)
        }
      })
    }
  }
}
</script>

