<template>
    <!-- 工程管理 新增、编辑 表单组件 -->
    <div>
        <el-form
            label-width="100px"
            size="medium"
            ref="projectParamsRef"
            :model="projectParams"
            :rules="projectParamsRules"
        >
          <el-row type="flex" justify="space-between" :gutter="24">
            <el-col :span="12">
              <el-form-item label="班组名称" prop="teamName">
                <el-input :maxlength="50" v-model="projectParams.teamName" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班组长" prop="relId">
                <el-select
                  v-model="projectParams.relId"
                  clearable
                  filterable
                  placeholder="请选择"
                  @change="leaderChange"
                >
                  <el-option
                    v-for="item in leaderRange"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span style="float: left">{{ item.label }}</span>
                    <span style="padding-left: 25px">{{ item._idCard }}</span>
                    <span style="float: right">{{ item._relPhone }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-between" :gutter="24">
            <el-col :span="12">
              <el-form-item label="所属工程" prop="proId">
                <el-select
                  v-model="projectParams.proId"
                  clearable
                  filterable
                  placeholder="请选择"
                  @change="projChange"
                >
                  <el-option
                    v-for="item in projRange"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      <div style="margin-left: 20px; margin-bottom: 15px">选择工程成员</div>

      <TableModel
        :columnsList="columnsListCrew"
        :request-api="() => {
          if(!this.crewParams) {
            return queryIsAllApi()
          } else {
            return queryCrewSelApi(this.crewParams.id)
          }
        }"
        ref="tableRef"
        @transIdList="getIdList"
        :show-btn-crews="false"
        :show-right-tools="false"
        style="margin-bottom: 100px"
        :selectable="(row) => {
          return row.id !== ableSelect
        }"
      >
        <template slot="handle" slot-scope="{ data }">
          <i
            style="font-size: 30px; color: red; cursor: pointer"
            class="el-icon-remove"
            @click="delCrew(data)"
            v-if="ableSelect !== data.id"
          ></i>
        </template>
        <template slot="idCard" slot-scope="{ data }">
          {{ idCardCrypto(data.idCard) || '-' }}
        </template>
        <template slot="relPhone" slot-scope="{ data }">
          {{ phoneCrypto(data.relPhone) || '-' }}
        </template>
      </TableModel>

      <div
        style="display: flex; justify-content: right"
      >
        <el-button type="success" @click="onSubmit">确认</el-button>
        <el-button
          @click="
            () => {
                this.$emit('closeDialog')
            }
        "
        >取消</el-button
        >
      </div>

    </div>
</template>

<script>
import { commonMixin } from '@/views/base/mixins/common'
import { columnsListCrew } from '../config-crew'
import {
  addCrewApi,
  editCrewApi,
  queryLeaderApi,
  queryIsAllApi,
  queryProjApi,
  queryCrewSelApi
} from '@/api/base/crew'
export default {
    name: 'FormPerson',
    props: {
        crewParams: {
            type: Object,
            default: () => null,
        },
    },
    mixins: [commonMixin],
    components: {  },
    created() {
      // this.getRanges()
    },
   async mounted() {
      this.open = true
      if (this.crewParams) {
          this.crewParams.proId = Number(this.crewParams.proId)
          this.ableSelect = this.crewParams.relId
          Object.assign(this.projectParams, this.crewParams)
          this.subSort = 2
      } else {
          this.subSort = 1
      }
      await this.getRanges()
      this.open = false
    },
    data() {
        return {
            columnsListCrew,
            open: false,
            exportList: [],
            subSort: '', // 提交类型：新增 1 / 修改 2
            ableSelect: undefined,
            projectParams: {
              teamName: undefined, //班组名称
              relId: undefined, //班组长
              proId: undefined, // 所属工程
            },
            // 校验规则
            projectParamsRules: {
              teamName: [
                  {
                      required: true,
                      message: '请输入班组名称',
                      trigger: 'blur',
                  },
              ],
              relId: [
                {
                  required: true,
                  message: '请选择班组长',
                  trigger: 'blur',
                },
              ],
              proId: [
                {
                  required: true,
                  message: '请选择所属工程',
                  trigger: 'blur',
                },
              ],
            },
            // 各类下拉
            leaderRange: [],
            projRange: []
        }
    },
    methods: {
        queryIsAllApi,
        queryCrewSelApi,
        getIdList(idList) {
          this.exportList = []
          idList.forEach(item => {
            this.exportList.push(item.id)
          })
        },
        /** 获取各类下拉框 */
        async getRanges() {
          if(this.subSort === 1) {
            // 获取班组长下拉选
            let leaderRes = await queryLeaderApi({
              isAll: 0
            })
            this.leaderRange = leaderRes.data.map(item => {
              return {
                label: item.relName,
                value: item.id,
                idCard: item.idCard,
                relPhone: item.relPhone,
                _idCard: this.idCardCrypto(item.idCard),
                _relPhone: this.phoneCrypto(item.relPhone)
              }
            })
          } else {
            // 获取班组长下拉选
            let _leaderRes = await queryCrewSelApi(this.crewParams.id)
            this.leaderRange = _leaderRes.data.map(item => {
              return {
                label: item.relName,
                value: item.id,
                idCard: item.idCard,
                relPhone: item.relPhone,
                _idCard: this.idCardCrypto(item.idCard),
                _relPhone: this.phoneCrypto(item.relPhone)
              }
            })
          }
          // 获取所属工程下拉选
          let projRes = await queryProjApi({
            isAll: 0
          })
          this.projRange = projRes.data.map(item => {
            return {
              label: item.proName,
              value: item.id
            }
          })
        },
        /** 改变树结构 */
        changeTree(leaf) {
          leaf.map(item => {
            item.value = item.id
            if(item.children) {
              this.changeTree(item.children)
            }
          })
          return leaf
        },
        leaderChange(e) {
          this.leaderRange.forEach(item => {
            if(e === item.value) {
              this.ableSelect = e
              this.projectParams.relName = item.label
              this.projectParams.relPhone = item.relPhone
            }
          })
        },
        projChange(e) {
          this.projRange.forEach(item => {
            if(e === item.value) {
              this.projectParams.proName = item.label
            }
          })
        },
        delCrew(v) {
          this.$modal
            .confirm('确定移除此项吗？')
            .then(() => {
              this.$refs.tableRef.tableList.forEach((item, index) => {
                if(item.id === v.id) {
                  this.$refs.tableRef.tableList.splice(index, 1)
                }
              })
            })
            .catch(() => {})
        },
        /** 级联选择器改变 */
        handleCas(e) {
          this.projectParams.impUnit = e[e.length - 1]
        },
        /** 确认按钮 */
        onSubmit() {
            this.$refs.projectParamsRef.validate(valid => {
                if (valid) {
                    this.projectParams.idList = this.exportList
                    console.log('校验通过', this.projectParams, this.subSort)
                    // 1. 表单校验通过后调后台 Api
                    if(this.subSort === 1) {
                      addCrewApi(this.projectParams).then(res => {
                        this.$modal.msgSuccess('操作成功')
                        // 2. 成功之后通知父组件关闭弹框
                        this.$emit('closeDialog', true)
                      }).catch(err => {
                        console.log(err)
                      })
                    } else if(this.subSort === 2) {
                      editCrewApi(this.projectParams).then(res => {
                        this.$modal.msgSuccess('操作成功')
                        // 2. 成功之后通知父组件关闭弹框
                        this.$emit('closeDialog', true)
                      }).catch(err => {
                        console.log(err)
                      })
                    }
                }
            })
        },
    },
}
</script>

<style scoped>
::v-deep .el-select {
    width: 100%;
}
::v-deep .el-form-item__label{
  font-weight: normal;
}
</style>
