<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" >
      <el-form-item label="班组名称:" prop="name">
        <el-input
          v-model.trim="queryParams.name"
          placeholder="请输入班组名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="责任人:" prop="dutyName">
        <el-select v-model="queryParams.dutyName"   placeholder="请选择责任人" style="width: 140px" >
          <el-option
            v-for="item in zrr"
            :key="item.name"
            :label="item.name"
            :value="item.name"
            clearable
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="right">
        <el-button plain size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
      <br>
      <el-button
        type="primary"
        size="mini"
        @click="handleAdd"
      >新增</el-button>
    </el-form>
    <el-table v-loading="loading" :data="adminList" style="margin-top:20px;" border>
      <el-table-column label="班组名称" align="center" prop="name"  show-overflow-tooltip />
      <el-table-column label="责任人" align="center" prop="dutyName"  show-overflow-tooltip />
      <el-table-column label="联系方式" align="center" prop="dutyPhone"  show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime"  show-overflow-tooltip />
      <el-table-column label="创建人" align="center" prop="createBy"  show-overflow-tooltip />
      <el-table-column label="修改时间" align="center" prop="updateTime"  show-overflow-tooltip />
      <el-table-column label="修改人" align="center" prop="updateBy"  show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            class="lans"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            class="hongs"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改、新增对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :before-close="cancel" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="auto" >
        <el-row :gutter="20">
          <el-col :span="12" >
            <el-form-item label="班组名称" prop="name">
              <el-input v-model="form.name" style="width: 160px" placeholder="请填写班组名称" @input="onInput()" maxlength="15" show-word-limit />
            </el-form-item>
          </el-col>
          <div class="btn" style="text-align: left;margin:0 auto 30px;float:right">
            <el-button type="primary"  size="mini" @click="addItem">新增人员</el-button>
          </div>
          <el-table :data="list" border   stripe height="200" :rules="rules2" >
            <el-table-column label="序号" width="80px" align='center'>
              <template slot-scope="scope">
                <span>{{ scope.$index +1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="switch" label="负任人" align='center'>
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.switch"
                  @change="handleStatusChange(scope.row,scope.$index)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" align='center'>
              <template slot-scope="scope">
                <span v-if="!scope.row.isEgdit">{{scope.row.name}}</span>
                <el-input v-if="scope.row.isEgdit" v-model="scope.row.name"></el-input>
              </template>
            </el-table-column>
             <el-table-column prop="phone" label="手机号" align='center'>
              <template slot-scope="scope">
                <span v-if="!scope.row.isEgdit">{{scope.row.phone}}</span>
                <el-input v-if="scope.row.isEgdit" v-model="scope.row.phone"  maxlength="11" ></el-input>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align='center' >
              <template slot-scope="scope">
                <el-button v-if="!scope.row.isEgdit" type="primary" size="small" @click='edit(scope.$index,scope.row)' icon="el-icon-edit" plain></el-button>
                <el-button v-if="scope.row.isEgdit" type="success" size="small" @click='editSuccess(scope.$index,scope.row)' icon="el-icon-check" plain></el-button>
                <el-button @click.native.prevent="deleteItem(scope.$index, list)" type="danger" size="small" icon="el-icon-delete" plain></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" plain>取 消</el-button>
      </div>
    </el-dialog>
    <el-pagination
      style="bottom:0px"
      background
      @current-change="handleCurrentChange1"
      :page-sizes="[10, 15, 20, 30]"
      @size-change="handleSizeChange1"
      :current-page="queryParams.pageNo"
      :page-size="queryParams.pageSize"
      layout="sizes,prev, pager, next"
      :total="totalCount1"
    >
    </el-pagination>
    <a href="" download="" id="xz" style="position: absolute;z-index: -1;opacity: 0;"></a>
  </div>
</template>
<script>
import { addDevopsTeam, delDevopsTeam, updateDevopsTeam, getDevopsTeam, getTD } from "@/api/MochaITOM/crew";
export default {
  name: "DevopsTeam",
  data() {
    return {
      exportLoading:false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      totalCount1:undefined,
      totalCount2:undefined,
      // 参数表格数据
      adminList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 15,
        name: undefined,
        dutyName:undefined,
        pageNo:1,
        pageSize:15,
      },
      // 查询参数
      queryParams2: {
        current: 1,
        size: 15,
        pageNo:1,
        pageSize:15,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "班组名称不能为空",  trigger: "blur"  }
        ],
      },
      rules2: {

        name: [
          { required: true, message: "姓名不能为空",  trigger: "blur"  }
        ],
        phone: [
          { required: true, message: "手机号不能为空",  trigger: "blur"  },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],

      },
      list: [
        {
        name:undefined,
        phone:undefined,
        switch:false,
        label:false,
        userId:1,
        },
      ],
      //责任人
      zrr:[]
    };
  },
  created() {
    this.getList();//初始化table
  },
  methods: {
    //分页查询
    handleCurrentChange1(val) {
      this.queryParams.pageNo = val;
      this.getList();
    },
    //分页查询
    handleSizeChange1(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    //分页查询
    handleCurrentChange2(val) {
      this.queryParams2.pageNo = val;
      this.getList();
    },
    //分页查询
    handleSizeChange2(val) {
      this.queryParams2.pageSize = val;
      this.getList();
    },
    //新增数据
    addItem() {
      let item = {
        name:undefined,
        phone:undefined,
        switch:false,
        label:1,
        userId:1,
      }
      this.list.push(item)
    },
    //删除数据
    deleteItem(index, list) {
      list.splice(index, 1);
    },
    //编辑数据
    edit(index, row) {
      this.$set(row, 'isEgdit', true)
    },
    //编辑成功
    editSuccess(index, row) {
      this.$set(row, 'isEgdit', false)
    },
    handleStatusChange(row,index){
      if(row.switch === true){
        row.label = 2
      }else{
        row.label = 1
      }
      for(let i = 0;i<this.list.length;i++){
        if(i != index){
          this.list[i].label = 1
          this.list[i].switch = 1
        }
      }
    },
    //强制el-input刷新
    onInput(){
        this.$forceUpdate();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //手机号验证
    testPhone(str) {
      // const reg = /^1[3|4|5|7|8|6|9][0-9]\d{8}$/;
      // return reg.test(str);
    },
    vaildPhone(value) {
      if (!this.testPhone(value)) {
        this.$message.warning("请输入正确的手机号码");
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        dutyName:undefined,
        current:1,
        size:15,
        pageSize:15,
        pageNo:1,
      }
      // this.resetForm("queryForm");
      this.handleQuery();
    },
    // 表单重置
    reset() {
      this.form = {};
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      getDevopsTeam(this.queryParams).then(response => {
        if(response.data.pageList.length>0){
          this.adminList = response.data.pageList;
          this.totalCount1 = response.data.totalCount;
          if(this.zrr.length>0){

          }else{
            for(let i=0;i<this.adminList.length;i++){
              this.zrr[i] = {}
              this.zrr[i].name = this.adminList[i].dutyName
            }
          }
          this.loading = false;
        }else{
          this.adminList = []
          this.loading = false;
        }

      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "修改";
      this.form = JSON.parse(JSON.stringify(row))
      this.list = this.form.userIds
      getTD({teamId:this.form.id,current:1,size:20}).then(res =>{
        let arr = res.data
        for(let i = 0;i<arr.length;i++){
          if(arr[i].label == "1"){
            arr[i].switch = false
          }else{
            arr[i].switch = true
          }
        }
        this.list = arr
        this.open = true;
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
      this.list = []
    },
    /** 提交按钮 */
    submitForm(row) {
      this.form.userIds = []
      this.form.userIds = this.list
      this.$refs["form"].validate(valid => {
        if (valid) {
          let arr = this.form.userIds
          if(arr.length>0){
            for(let i = 0;i<arr.length;i++){
              if(!arr[i].name){
                this.$message.error("姓名不能为空");
                return
              }
              if(!arr[i].phone){
                this.$message.error("电话不能为空");
                return
              }
            }
          }
          for(let i =0;i<arr.length;i++){
            for(let a= 0;a<arr.length;a++){
              if(a != i){
                if(arr[a].name == arr[i].name){
                  this.$message.error("姓名不能重复");
                  return
                }
                if(arr[a].phone == arr[i].phone){
                  this.$message.error("手机号不能重复");
                  return
                }
              }
            }
          }
          this.loading = true
          if (this.form.id != undefined) {
            updateDevopsTeam(this.form).then(response => {
              this.loading = false,
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            }).catch(()=>{
              this.loading = false
            })
          } else {
            addDevopsTeam(this.form).then(response => {
              this.loading = false
              if(response.status == "SUCCESS"){
                this.$message.success("新增成功");
                this.open = false;
                this.getList();
              }
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDevopsTeam(ids);
        }).then(() => {
          this.getList();
          this.$message.success("删除成功");
        }).catch(() => {});
    },
  }
};
</script>
