<template>
  <div class="dialog-h-content scroll-h">
    <div class="div_table">
      <el-button size="small"
                 class="diy-button--add"
                 @click="handleAdd">新增</el-button>

      <el-table class="table"
                :data="tableData"
                border
                :height="tableHeight"
                v-loading="tableLoading"
                :header-cell-style="{background:'#2195FE',color:'#FFFFFF'}"
                style="width: 100%">
        <el-table-column label="序号"
                         header-align="center"
                         align="center"
                         type="index"
                         width="50">
        </el-table-column>

        <el-table-column prop="reviewTime"
                         header-align="center"
                         align="center"
                         label="复查时间"
                         width="250">
          <template slot-scope="scope">
            <div v-if="scope.row.isEdit">
              <el-date-picker v-model="scope.row.reviewTime"
                              value-format="yyyy-MM-dd"
                              type="date"
                              placeholder="选择日期">
              </el-date-picker>
            </div>
            <span v-else>{{scope.row.reviewTime}}</span>
          </template>

        </el-table-column>
        <el-table-column prop="ninePlaceName"
                         header-align="center"
                         align="center"
                         label="分队名称"
                         width="280">

          <template slot-scope="scope">
            <div v-if="scope.row.isEdit">
              <el-select class="item_width_1"
                         v-model="scope.row.placePatrolTeamId"
                         placeholder="请选择"
                         clearable>
                <el-option v-for="(item,index) in teamsList"
                           @click.native="hancleChangeTeam(scope.row,index,scope.$index)"
                           :key="item.teamId"
                           :label="item.teamName"
                           :value="item.teamId">
                </el-option>
              </el-select>
            </div>
            <span v-else>{{scope.row.placePatrolTeamName}}</span>
          </template>
        </el-table-column>

        <el-table-column prop="inspectorsNames"
                         header-align="center"
                         align="center"
                         label="检查人员"
                         min-width="380">

          <template slot-scope="scope">
            <div v-if="scope.row.isEdit">
              <el-checkbox-group style="display:flex;flex-wrap:wrap"
                                 v-model="scope.row.inspectorArray">
                <el-checkbox v-for="item in scope.row.inspectorsList"
                             :key="item.id"
                             :label="item.id">{{item.name}}</el-checkbox>

              </el-checkbox-group>
            </div>
            <span v-else>{{scope.row.inspectorsNames}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="reviewResult"
                         header-align="center"
                         align="center"
                         label="复查结论"
                         width="120">
          <template slot-scope="scope">
            <div v-if="scope.row.isEdit">
              <el-select class="item_width_2"
                         v-model="scope.row.reviewResult"
                         placeholder="全部"
                         clearable>
                <el-option v-for="item in resultList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </div>
            <span v-else>{{scope.row.reviewResult==='0'?'合格':'不合格'}}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作"
                         fixed="right"
                         width="180"
                         header-align="center"
                         align="center"
                         class="operate">
          <template slot-scope="scope">
            <el-button v-if="scope.row.isEdit"
                       type="text"
                       style="color:#00A7A9;text-decoration: underline;"
                       size="small"
                       @click="handleComfirm(scope.row,scope.$index)">保存</el-button>
            <el-button v-if="!scope.row.isEdit"
                       type="text"
                       style="color:#1C6AFD;text-decoration: underline;"
                       size="small"
                       @click="handleEdit(scope.row,scope.$index)">修改</el-button>

            <el-button type="text"
                       style="color:#D51010;text-decoration: underline;"
                       size="small"
                       @click="handleDelete(scope.row,scope.$index)">删除</el-button>

          </template>
        </el-table-column>
      </el-table>

    </div>
    <!-- <div class="div_btn">
      <el-button @click="handleCancle">取 消</el-button>
  
    </div> -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'

let loading // 加载动画
export default {
  data () {
    return {
      tableLoading: false,
      placePatrolRecordId: '',
      tableData: [],


    }
  },
  components: {},
  mounted () {

  },

  methods: {

    async initTable (placePatrolRecordId) {
      this.placePatrolRecordId = placePatrolRecordId
      await this.loadTeams()

      await this.loadTable()

    },


    //加载分队
    async loadTeams () {
      const url = '/gov/org/placepatrolteam/getlist'
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/placepatrolteam/getlist'
      let params = {
        isPage: false
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.teamsList = data.list


      } else {
        this.$message.error(msg)
      }
    },

    //点击分队切换人员
    async hancleChangeTeam (row, index, tableIndex) {
      this.tableData[tableIndex].inspectorArray = [...[]]
      let teamId = this.teamsList[index].teamId
      await this.loadInspectors(teamId, tableIndex)
    },

    //加载分队下人员
    async loadInspectors (teamId, tableIndex) {

      const url = '/gov/org/placepatrolteamstaff/getlist'
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/placepatrolteamstaff/getlist'
      let params = {
        teamId: teamId
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        // let obj = this.tableData[tableIndex]
        this.tableData[tableIndex].inspectorsList = [...data]
        // this.tableData[tableIndex]=
        //         obj.inspectorsList = data
        //         this.$set(this.tableData, tableIndex, obj)
        console.log(this.tableData)
      } else {
        this.$message.error(msg)
      }
    },
    //加载form
    async loadTable () {
      this.tableLoading = true
      const url = '/gov/org/placepatrolreviewrecord/getlist'
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/placepatrolreviewrecord/getlist'
      let params = {
        placePatrolRecordId: this.placePatrolRecordId
      }

      const { data, code, msg } = await requestPost(url, params)
      this.tableLoading = false
      if (code === 0) {

        if (data.list && data.list.length > 0) {
          data.list.forEach(item => {
            item.isEdit = false
            item.isNew = false
            let arrayInspectors = item.inspectors.split(',')
            item.inspectorArray = [...arrayInspectors]

            let arrayReviewTime = item.reviewTime.split(' ')
            item.reviewTime = arrayReviewTime[0]
          });

          this.tableData = [...data.list]
        } else {
          this.tableData = []
        }

      } else {
        this.$message.error(msg)
      }
    },

    handleAdd () {
      let obj = {
        isNew: true,//是否新增
        isEdit: true,//是否编辑
        placePatrolRecordId: this.placePatrolRecordId,
        reviewTime: '',
        placePatrolTeamId: '',
        inspectors: '',
        inspectorArray: [],
        inspectorsList: [],
        reviewResult: '',
      }
      this.tableData.push(obj)
    },

    async handleEdit (row, tableIndex) {
      let teamId = row.placePatrolTeamId
      await this.loadInspectors(teamId, tableIndex)

      let rowData = JSON.parse(JSON.stringify(row))
      rowData.isEdit = true
      rowData.isNew = false
      rowData.inspectorArray = rowData.inspectors.split(',')

      console.log(rowData)
      this.$set(this.tableData, tableIndex, rowData)
    },

    async handleComfirm (row, tableIndex) {
      let valiMsg = this.validata(row)
      if (valiMsg) {
        this.$message({
          type: 'warning',
          message: valiMsg
        })
        return false
      }

      this.addReview(row, tableIndex)

    },
    async addReview (row, tableIndex) {

      let url = "/gov/org/placepatrolreviewrecord/add"
      if (row.placePatrolReviewRecordId) {
        url = "/gov/org/placepatrolreviewrecord/edit"
      }

      let params = JSON.parse(JSON.stringify(row))
      params.inspectors = params.inspectorArray.join(',')
      params.reviewTime = params.reviewTime + ' 00:00:00'

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        let array = data.reviewTime.split(' ')
        data.reviewTime = array[0]
        data.isEdit = false
        data.isNew = false

        this.$set(this.tableData, tableIndex, data)

      } else {

        this.$message.error(msg)
      }

    },

    validata (row) {
      let message = ''
      if (row.reviewTime === '') {
        message = message + '复查时间不能为空；'
      }
      if (row.placePatrolTeamId === '') {
        message = message + '分队名称不能为空；'
      }
      if (row.inspectorArray.length === 0) {
        message = message + '检查人员不能为空；'
      }
      if (row.reviewResult === '') {
        message = message + '复查结论不能为空；'
      }
      return message
    },

    async handleDelete (row, tableIndex) {

      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          if (row.placePatrolReviewRecordId) {//存在id，调用服务删除
            this.deleteRecord(row, tableIndex)
          } else {//不存在id，直接删除数组数据
            this.tableData.splice(tableIndex, 1);
          }

        })
        .catch(err => {
          if (err == "cancel") {

          }

        });
    },

    async deleteRecord (row, tableIndex) {

      const url = "/gov/org/placepatrolreviewrecord/del"

      let params = {
        placePatrolReviewRecordId: row.placePatrolReviewRecordId
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        // this.$message({
        //   type: "success",
        //   message: "删除成功"
        // });

        this.tableData.splice(tableIndex, 1);
      } else {
        this.$message.error(msg)
      }
    },

    handleCancle () {
      this.$emit('dialogCancle')

    },


    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    tableHeight () {

      return (this.clientHeight - 360)

    },

    ...mapGetters(['clientHeight'])

  },
  props: {


    resultList: {
      type: Array,
      default: []
    }
  }
}
</script>


<style lang="scss" scoped >
@import "@/assets/scss/buttonstyle.scss";
.item_width_1 {
  width: 250px;
}
.item_width_2 {
  width: 100px;
}
.div_table {
  // background: #ffffff;
  // box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.1);
  // border-radius: 4px;

  .table {
    margin-top: 20px;
  }
}
.div_btn {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
