<template>
  <div class="app-container">
    <div class="filter-container">

      <el-input v-model="search.keyWord" placeholder="关键字" style="width: 200px;" class="filter-item" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>

      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreateAdd">
        增加人员
      </el-button>
      <el-button type="green" @click="batchAddPerson">批量增加人员</el-button>
    </div>
    <el-table
      :data="tableData"
      v-loading="listLoading"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      default-expand-all>
      <el-table-column
        prop="userName"
        label="人员名称">
      </el-table-column>
      <el-table-column label="处理订单数量" align="center" prop="processOrderCount" />
      <el-table-column label="处理图片P数" align="center" prop="processImagePCount">
      </el-table-column>
<!--      <el-table-column align="center" label="状态" class-name="status-col" width="100">-->
<!--        <template slot-scope="{row}">-->
<!--          <el-tag v-if="row.voidFlag==0" type="success">-->
<!--            正常-->
<!--          </el-tag>-->
<!--          <el-tag v-else-if="row.voidFlag==1" type="danger">-->
<!--            禁用-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" fixed="left" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button @click="handleUpdate(row)" type="primary" size="mini">
            编辑
          </el-button>
          <el-button @click="editStatus(row.id)" type="danger" size="mini">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="listData.total>0" :total="listData.total" :page.sync="listData.page" :limit.sync="listData.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogVisible" width="800px">
      <el-form label-width="130px" label-position="right">
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本信息" name="first">
            <el-dialog :close-on-click-modal="false" title="选择负责人" append-to-body :visible.sync="userInfoVisible" width="70%">
              <user :is-choose="true" @chooseUser='chooseUser'></user>
            </el-dialog>
            <el-form-item label="人员名称">
              <el-button @click="openChooseUser" :disabled="dialogStatus == 2" plain type="primary">{{form.userName ? form.userName: '选择人员'}}</el-button>
            </el-form-item>
            <el-form-item label="处理订单数量">
              <el-input v-model="form.processOrderCount"></el-input>
            </el-form-item>
            <el-form-item label="处理图片P数">
              <el-input v-model="form.processImagePCount"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="班组档案" name="second">
            <el-button type="primary" style="margin-bottom: 10px" @click="addWorkTeam">添加</el-button>
            <el-dialog
              title="选择班组"
              :visible.sync="workTeamVisible"
              :close-on-click-modal="false"
              append-to-body>
              <div class="filter-container">
                <el-input v-model="workTeamSearch.keyWord" placeholder="关键字" style="width: 200px;" class="filter-item" />
                <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getTeamList">
                  搜索
                </el-button>
                <el-button class="filter-item" type="success" icon="el-icon-search" @click="saveWorkTeamSelection">
                  保存
                </el-button>
              </div>
              <el-table
                :data="workTeamList"
                ref="workTeamTable"
                style="width: 100%;margin-bottom: 20px;"
                border
                @selection-change="workTeamSelectionChange">
                <el-table-column
                  type="selection"
                  width="55">
                </el-table-column>
                <el-table-column
                  prop="teamName"
                  label="班组名称">
                </el-table-column>
                <el-table-column
                  prop="managerUserName"
                  label="负责人">
                </el-table-column>
              </el-table>
            </el-dialog>

            <el-table
              :data="checkedTeamList"
              style="width: 100%;margin-bottom: 20px;"
              row-key="id"
              ref="checkedTeamList"
              border
              default-expand-all>
              <el-table-column
                prop="teamName"
                label="班组名称">
              </el-table-column>
              <el-table-column
                prop="managerUserName"
                label="负责人">
              </el-table-column>
              <el-table-column
                label="操作">
                <template slot-scope="{row}">
                  <el-button @click="deleteWorkTeam(row.id)" type="danger" size="mini">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

          </el-tab-pane>
          <el-tab-pane label="产品档案" name="third">
            <el-button type="primary" style="margin-bottom: 10px" @click="addProduct">添加</el-button>
            <el-dialog
              title="选择产品"
              :visible.sync="productVisible"
              :close-on-click-modal="false"
              append-to-body>
              <div class="filter-container">
                <el-input v-model="productSearch.keyWord" placeholder="关键字" style="width: 200px;" class="filter-item" />
                <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getProductInfo">
                  搜索
                </el-button>
                <el-button class="filter-item" type="success" icon="el-icon-search" @click="saveProductSelection">
                  保存
                </el-button>
              </div>
              <el-table
                :data="productList"
                ref="productTable"
                style="width: 100%;margin-bottom: 20px;"
                border
                @selection-change="productSelectionChange">

                <el-table-column
                  type="selection"
                  width="55">
                </el-table-column>
                <el-table-column
                  prop="productName"
                  label="产品名称">
                </el-table-column>
              </el-table>
            </el-dialog>

            <el-table
              :data="checkedProductList"
              style="width: 100%;margin-bottom: 20px;"
              row-key="id"
              border
              default-expand-all>
              <el-table-column
                prop="productName"
                label="产品名称">
              </el-table-column>
              <el-table-column
                label="操作">
                <template slot-scope="{row}">
                  <el-button @click="deleteProduct(row.id)" type="danger" size="mini">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='1'?addBtn():editBtn()">确 定</el-button>
      </div>
    </el-dialog>
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
    <el-dialog title="批量添加人员" :visible.sync="batchAddDialog">
      <user :key="timer" :is-choose="true" :type="1"  @chooseUser='chooseUsers' :table-size="'mini'"></user>
    </el-dialog>
  </div>
</template>

<script>
import {
  getWorkTeamPerson,
  addWorkTeamPerson,
  getWorkTeamPersonInfo,
  updateWorkTeamPerson,
  batchAddWorkTeamPerson
} from '@/api/baseInfo/workTeam/workTeamPerson'
import { getWorkTeamList } from '@/api/baseInfo/workTeam/workTeam'
import { getProductInfoList } from '@/api/productFile/productInfo.js'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import User from '@/views/system/user/user'

const form = {
  idTeam: undefined, // 班组id,
  idLoginUser: undefined, // 用户id，增加时从【用户管理】中选择,
  userName: undefined, // 人员名称，增加时从【用户管理】中选择,
  processOrderCount: undefined, // 处理订单数量--针对修图班组为【可暂停单数】,
  processImagePCount: undefined, // 处理图片P数--针对修图班组为【任务P数上限】,
  processWorkTeamIds: undefined, // 处理班组档案id字符串，逗号分隔,
  processProductIds: undefined // 处理产品档案id字符串，逗号分隔,
}

export default {
  name: 'WorkTeamPerson',
  components: {
    User,
    Cancledialog
  },
  data() {
    return {
      idTeam: '',
      teamName: '',
      activeName: 'first',
      dialogStatus: 1, // 1增加，2修改
      dialogTitle: '',
      dialogVisible: false,
      timer: '',
      batchAddDialog: false,

      workTeamVisible: false,
      productVisible: false,

      search: {
        keyWord: ''
      },
      form: Object.assign({}, form),

      confirmdialog: false,
      listLoading: false,
      tableData: [],

      listData: {
        total: 0,
        page: 1,
        pageSize: 10
      },

      userInfoVisible: false,
      // 添加班组档案
      workTeamSearch: {
        keyWord: ''
      },
      workTeamList: [],
      checkedTeam: [],
      checkedTeamList: [],

      // 选择产品
      productList: [],
      productSearch: {
        keyWord: ''
      },
      productListData: {
        total: 0,
        page: 1,
        pageSize: 10
      },
      checkedProduct: [],
      checkedProductList: []
    }
  },
  created() {
    this.idTeam = this.$route.query.idTeam
    this.teamName = this.$route.query.teamName
    this.tempRoute = Object.assign({}, this.$route)
    this.setTagsViewTitle()


  },
  mounted() {
    this.getList()
    this.getTeamList()
    this.getProductInfo()
  },
  methods: {
    // 设置标签名称
    setTagsViewTitle() {
      const title = '班组人员'

      // console.log("tempRoute2",this.tempRoute);
      const route = Object.assign({}, this.tempRoute, { title: `${this.teamName}-${title}` })
      // console.log("route",route)
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    // 获取列表
    getList() {
      const _that = this
      _that.listLoading = true
      const params = _that.search
      const data = {
        'idTeam': _that.idTeam,
        'params': JSON.stringify(params)
      }
      // console.log(data);
      getWorkTeamPerson(data).then(response => {
        console.log(response)
        const data = response.data
        // //  组合表单数据
        _that.tableData = data
        _that.listData.total = response.total
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
    },

    // 批量增加
    batchAddPerson() {
      this.batchAddDialog = true

      this.timer = new Date().getTime()
    },
    chooseUsers(row){
      const _that = this
      console.log(row);
      var ids = []
      row.forEach(item =>{
        ids.push(item.id)
      })
      var data = {
        idTeam: _that.idTeam,
        idUsers: ids.join(',')
      }
      batchAddWorkTeamPerson(data).then((res) => {
        console.log(res);
        if(res.httpCode == 200 ) {

          _that.$message.success('添加成功')
          _that.batchAddDialog = false
          _that.tableRefresh()
        }
      })

    },

    // 增加班组人员
    handleCreateAdd() {
      const _that = this
      _that.form = Object.assign({}, form)
      _that.dialogTitle = '增加班组人员'
      _that.dialogStatus = '1'
      _that.activeName = 'first'
      _that.dialogVisible = true
      _that.checkedTeamList = []
      _that.checkedProductList = []
    },
    // 增加档案
    addBtn() {
      const _that = this
      _that.form.idTeam = _that.idTeam
      var ids1 = []
      _that.checkedTeamList.forEach(item => {
        ids1.push(item.id)
      })
      _that.form.processWorkTeamIds = ids1.join(',')

      var ids2 = []
      _that.checkedProductList.forEach(item => {
        ids2.push(item.id)
      })
      _that.form.processProductIds = ids2.join(',')
      const info = JSON.stringify(_that.form)
      const data = {
        'teamPerson': info
      }
      // console.log(data);
      // return

      addWorkTeamPerson(data).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '增加成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 唤起修改
    handleUpdate(row) {
      const _that = this

      _that.dialogTitle = '修改班组人员'
      _that.dialogVisible = true
      _that.dialogStatus = '2'
      _that.activeName = 'first'
      const data = {
        idPerson: row.id
      }
      // console.log(data);
      getWorkTeamPersonInfo(data).then(res => {
        console.log(res)
        const data = res.data

        _that.form = {
          id: data.id,
          idTeam: data.idTeam,
          idLoginUser: data.idLoginUser,
          userName: data.userName,
          processOrderCount: data.processOrderCount,
          processImagePCount: data.processImagePCount,
          processWorkTeamIds: data.processWorkTeamIds,
          processProductIds: data.processProductIds
        }
        _that.checkedTeamList = data.processWorkTeamList
        _that.checkedProductList = data.processProductList
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 修改档案
    editBtn() {
      const _that = this
      var ids1 = []
      _that.checkedTeamList.forEach(item => {
        ids1.push(item.id)
      })
      _that.form.processWorkTeamIds = ids1.join(',')

      var ids2 = []
      _that.checkedProductList.forEach(item => {
        ids2.push(item.id)
      })
      _that.form.processProductIds = ids2.join(',')
      const info = JSON.stringify(_that.form)
      const data = {
        'teamPerson': info
      }
      // console.log(data);
      // return;

      updateWorkTeamPerson(data).then(res => {
        console.log(res)
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '修改成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 刷新变革
    tableRefresh() {
      // 刷新变革
      this.getList()
    },

    // 启用禁用
    editStatus(id) {
      const _that = this
      const teamPerson = {
        id: id
      }
      const params = {
        'teamPerson': JSON.stringify(teamPerson)
      }

      const url = '/doc/deleteWorkTeamPerson'
      _that.$refs.confirmDialog.updataClick(params, url)
    },

    // 搜索
    searchData() {
      this.listData.page = 1
      this.getList()
    },
    // 选择人员
    openChooseUser() {
      this.userInfoVisible = true
    },
    chooseUser(row) {
      console.log(row)
      var _that = this
      _that.userInfoVisible = false
      _that.form.idLoginUser = row.id
      _that.form.userName = row.userName
    },

    // 增加班组
    addWorkTeam() {
      const _that = this
      _that.workTeamVisible = true
      _that.checkedTeam = []
      _that.$nextTick(() => {
        _that.$refs.workTeamTable.clearSelection()
        if (_that.checkedTeamList) {
          _that.checkedTeamList.forEach(item => {
            _that.workTeamList.forEach(workTeam => {
              if(item.id == workTeam.id){
                _that.$refs.workTeamTable.toggleRowSelection(workTeam, true)
              }
            })
          })
        }
      })
    },

    // 获取班组列表
    getTeamList() {
      const _that = this
      const params = _that.workTeamSearch
      const data = {
        'params': JSON.stringify(params)
      }
      // console.log(data);
      getWorkTeamList(data).then(response => {
        console.log(response)
        const data = response.data
        // //  组合表单数据
        _that.workTeamList = data
        // console.log(_that.tableData)
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 选中事件
    workTeamSelectionChange(val) {
      console.log(val)
      var _that = this
      _that.checkedTeam = val
    },
    // 保存
    saveWorkTeamSelection() {
      var _that = this
      _that.workTeamVisible = false
      // var ids = []
      // _that.checkedTeam.forEach(item => {
      //   ids.push(item.id)
      // })
      _that.checkedTeamList = _that.checkedTeam
      // _that.form.processWorkTeamIds = ids.join(',')
    },
    // 删除
    deleteWorkTeam(id) {
      var _that = this
      _that.checkedTeamList.forEach((item, index) => {
        if (item.id == id) {
          _that.checkedTeamList.splice(index, 1)
        }
      })
    },
    // 增加产品
    addProduct() {
      const _that = this
      _that.productVisible = true
      _that.checkedProduct = []
      _that.$nextTick(() => {
        _that.$refs.productTable.clearSelection()
        if (_that.checkedProductList) {
          _that.checkedProductList.forEach(item => {
            _that.productList.forEach(productItem =>{
              if (item.id == productItem.id){
                _that.$refs.productTable.toggleRowSelection(productItem, true)
              }
            })
          })
        }
      })
    },
    // 获取产品列表
    getProductInfo() {
      const _that = this

      var params = _that.productSearch
      var data = {
        'params': JSON.stringify(params)
      }

      getProductInfoList(data).then(response => {
        console.log(response)
        const data = response.data
        // //  组合表单数据
        _that.productList = data
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    productSelectionChange(val) {
      this.checkedProduct = val
    },
    saveProductSelection() {
      var _that = this
      _that.productVisible = false
      _that.checkedProductList = _that.checkedProduct
    },
    deleteProduct(id){
      var _that = this
      _that.checkedProductList.forEach((item, index) => {
        if (item.id == id) {
          _that.checkedProductList.splice(index, 1)
        }
      })
    }

  }
}
</script>

<style lang="scss" scoped>
  .filter-container {
    margin-bottom: 15px;
  }
  .tableItemInput{
    width: 30%;
  }
</style>
