<template>
  <a-modal
    :title="modalTitle"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    class="ant-modal2"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <row-list :col="1" v-show="false">
        <row-item>
          <a-form-item>
            <a-input v-decorator="['id']" type="hidden"/>
          </a-form-item>
        </row-item>
      </row-list>
      <row-list :col="2">
        <!--<row-item>
          <a-form-item
            label="标题"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['title', {rules: [{required: true, message: '标题不能为空'}]}]"/>
          </a-form-item>
        </row-item>-->
        <row-item>
          <a-form-item
            label="调拨类型"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select @change="changeType" v-decorator="['type', { rules: [{required: true, message: '调拨类型不能为空'}]}]" placeholder="请选择">
              <a-select-option
                v-for="(label,value) in deptTypeMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="目标部门"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-tree-select
              style="width: 100%"
              :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
              :treeData="treeData"
              :treeNodeFilterProp="'title'"
              :showSearch="true"
              treeDefaultExpandAll
              :replaceFields="{value: 'id'}"
              v-decorator="['targetDept', {rules: [{required: true, message: '目标部门不能为空'}]}]"
              @change="deptChange"
              placeholder="请选择"
            >
            </a-tree-select>
          </a-form-item>
        </row-item>
        <row-item v-show="showTargetUserId">
          <a-form-item
            label="设备管理员"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select v-decorator="['targetUserId', {rules: [{required: showTargetUserId, message: '设备管理员不能为空'}]}]" placeholder="请选择">
              <a-select-option
                v-for="(item,index) in targetUser"
                :key="index"
                :label="item.realName"
                :value="item.userId">{{ item.realName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
      </row-list>
      <row-list :col="1">
        <row-item>
          <a-form-item
            label="备注"
            :labelCol="BaseTool.Constant.labelCol2"
            :wrapperCol="BaseTool.Constant.wrapperCol2"
          >
            <a-textarea
              :rows="4"
              v-decorator="['remark']"/>
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>

    <a-tabs type="card" default-active-key="1">
      <a-tab-pane key="1" tab="设备列表">
        <div class="table-operator">
          <a-button size="small" type="primary" @click="handleStandardSelect">
            <a-icon type="plus"/>
            添加
          </a-button>
          <a-button class="margin-left8" size="small" type="danger" @click="handleDel">
            <a-icon type="delete"/>
            删除
          </a-button>
        </div>
        <a-table
          bordered
          :data-source="data"
          :columns="columns"
          tableLayout="auto"
          rowKey="id"
          :scroll="{ x: 1600, y: BaseTool.Constant.scrollY }"
          :row-selection="rowSelection"
        >
          <span slot="action" slot-scope="record">
            <template>
              <a @click="handleView(record)">查看</a>
            </template>
          </span>
          <span slot="status" slot-scope="text">
            <badge :status="DictCache.COLOR.SB_INFO_STATUS[text]" :text="statusMap[text]" />
          </span>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <sb-info-select-modal-by-user ref="sbInfoSelectModalByUser" :type="'checkbox'" @selected="handleSbSelected"/>
    <detail ref="detailModal"/>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import SbInfoSelectModalByUser from '@/views/sb/info/modules/SbInfoSelectModalByFilter'
import Detail from '@/views/sb/info/modules/Detail'
import { addSbAllocateApply, updateSbAllocateApply } from '@/api/sb/allocate-apply'
import { fetchSbInfo } from '@/api/sb/info'
import { getDeptAllocateTree } from '@/api/upms/dept'
import { queryUserDeptByUserDeptId } from '@/api/upms/user-dept'

export default {
  name: 'BaseSbAllocateApply',
  components: {
    SbInfoSelectModalByUser,
    Detail
  },
  props: {
    applyFilter: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      levelMap: {},
      statusMap: {},
      type: null,
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      },
      treeData: [],
      showTargetUserId: false,
      targetUser: [],
      // 表头
      columns: [
        {
          title: '设备编号',
          dataIndex: 'no',
          width: 200
        },
        {
          title: '设备名称',
          dataIndex: 'name',
          width: 200
        },
        {
          title: '设备型号',
          dataIndex: 'model',
          width: 200
        },
        {
          title: '设备类型',
          dataIndex: 'type',
          width: 200,
          customRender: (text, record, index) => {
            return record.typeName
          }
        },
        {
          title: '生产商',
          dataIndex: 'producerId',
          width: 200,
          customRender: (text, record, index) => {
            return record.producerName
          }
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 200,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          key: 'action',
          width: '200px',
          align: 'center',
          fixed: 'right',
          scopedSlots: { width: 200, customRender: 'action' }
        }
      ],
      data: [],
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys
        }
      },
      // 下拉框map
      typeMap: {},
      deptTypeMap: {}
    }
  },
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_ALLOCATE_APPLY_TYPE)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_INFO_STATUS)
    this.levelMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_LEVEL)
  },
  methods: {
    base (record, dept) {
      this.visible = true
      this.deptTypeMap = {}
      if (this.applyFilter === 1 || this.applyFilter === 2) {
        // 我的调拨 主管调拨
        if (dept.nature === this.DictCache.VALUE.SYS_DEPT_NATURE.BAN_ZU) {
          this.type = this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT
          this.deptTypeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT] = this.typeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT]
        } else if (dept.nature === this.DictCache.VALUE.SYS_DEPT_NATURE.XIANG_MU_BU) {
          this.type = this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT
          this.deptTypeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT] = this.typeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT]
          this.deptTypeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT_TO_PROJECT] = this.typeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT_TO_PROJECT]
          this.deptTypeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT_COMPANY] = this.typeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT_COMPANY]
        } else if (dept.nature === this.DictCache.VALUE.SYS_DEPT_NATURE.FEN_GONG_SI) {
          this.type = this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.COMPANY_PROJECT
          this.deptTypeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.COMPANY_PROJECT] = this.typeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.COMPANY_PROJECT]
          this.deptTypeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.COMPANY_COMPANY] = this.typeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.COMPANY_COMPANY]
        } else {
          this.$message.error('该部门没有调拨功能')
          return
        }
      } else if (this.applyFilter === 3) {
        // 项目部设备主管调拨
        this.type = this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT
        this.deptTypeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT] = this.typeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT]
        this.deptTypeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT_TO_PROJECT] = this.typeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT_TO_PROJECT]
        this.deptTypeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT_COMPANY] = this.typeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.PROJECT_COMPANY]
      } else if (this.applyFilter === 4) {
        // 分公司设备主管调拨
        this.type = this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.COMPANY_PROJECT
        this.deptTypeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.COMPANY_PROJECT] = this.typeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.COMPANY_PROJECT]
        this.deptTypeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.COMPANY_COMPANY] = this.typeMap[this.DictCache.VALUE.SB_ALLOCATE_APPLY_TYPE.COMPANY_COMPANY]
      }

      const { form: { setFieldsValue } } = this
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.getDeptAllocateTree()
        this.$nextTick(() => {
          setFieldsValue({ type: this.type })
        })
        return
      }
      this.modalTitle = '编辑'
      this.type = record.type
      this.getDeptAllocateTree()
      // 日期处理
      record.startTime = this.BaseTool.Moment(record.startTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      record.endTime = this.BaseTool.Moment(record.endTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      this.data = record.sbInfos !== null ? record.sbInfos : []
      if (this.BaseTool.String.isNotBlank(record.targetUserId)) {
        this.getTargetUsers(record.targetDept).then(res => {
          this.showTargetUserId = true
        })
      } else {
        this.showTargetUserId = false
      }
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'type',
          'targetDept',
          'targetUserId',
          'remark'
        ])))
      })
    },
    getTargetUsers (deptId) {
      return queryUserDeptByUserDeptId({ deptId: deptId }).then(res => {
        this.targetUser = res.data
        return res.data
      })
    },
    getDeptAllocateTree () {
      getDeptAllocateTree({ allocateType: this.type }).then(res => {
        this.treeData = res.data
      })
    },
    deptChange (val, label, v) {
      const dept = v.triggerNode.dataRef.item
      if (this.BaseTool.Object.isNotBlank(dept) && dept.nature === this.DictCache.VALUE.SYS_DEPT_NATURE.BAN_ZU) {
        this.getTargetUsers(dept.deptId).then(res => {
          this.showTargetUserId = true
        })
      } else {
        const { form: { setFieldsValue } } = this
        setFieldsValue({ targetUserId: null })
        this.showTargetUserId = false
      }
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        if (this.data == null || this.data.length === 0) {
          this.$message.error('请选择设备')
          return
        }
        // 日期处理
        values.sbInfos = this.data
        values.type = this.type
        values.filter = this.applyFilter
        if (this.BaseTool.String.isBlank(values.id)) {
          addSbAllocateApply(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateSbAllocateApply(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleStandardSelect () {
      let sbFilter = 1
      if (this.applyFilter === 1) {
        // 我的调拨
        sbFilter = 1
      } else if (this.applyFilter === 2) {
        // 主管调拨
        sbFilter = 2
      } else if (this.applyFilter === 3) {
        // 项目部主管调拨
        sbFilter = 3
      } else if (this.applyFilter === 4) {
        // 分公司主管调拨
        sbFilter = 4
      }
      this.$refs.sbInfoSelectModalByUser.base({ filter: sbFilter, notStatusList: [this.DictCache.VALUE.SB_INFO_STATUS.IN_DIAOBO] })
    },
    changeType (value) {
      this.type = value
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        setFieldsValue({ targetDept: null })
      })
      this.getDeptAllocateTree()
    },
    handleDel () {
      const data = [...this.data]
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }
      this.data = data.filter(item => !this.selectedRowKeys.includes(item.id))
    },
    handleSbSelected (keys, rows) {
      const { data } = this
      const len = data.length
      for (let i = 0; i < rows.length; i++) {
        const row = rows[i]
        let flag = false
        for (let j = 0; j < len; j++) {
          if (row.id === data[j].id) {
            flag = true
          }
        }
        if (!flag) {
          data.push(row)
        }
      }
    },
    handleView (record) {
      fetchSbInfo({ id: record.id }).then(res => {
        const modal = this.$refs.detailModal
        modal.base(res.data)
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.data = []
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    }

  }
}
</script>
