<template>
  <div>
    <xy-dialog ref="dialog" :width="70" :is-show.sync="isShow" :type="'form'" :title="typeName" :form="form">
      <template v-slot:show>
        <div class="xy-table-item" style="padding: 0 20px;">
          <div class="xy-table-item-label" style="font-weight: bold;width:0;padding: 0;display: none;">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>
          </div>
          <div class="xy-table-item-content" style="flex-grow: 1;">
            <div class="courseName" v-if="type=='check' || type=='checkshow' ">
              <div>课程名称：{{subjectObj.title}}</div>
              <div>开课日期：{{subjectObj.date?subjectObj.date:'开课待定'}}</div>
              <div>课程体系：{{subjectObj.leibie}}</div>
            </div>
            <div>
              <lx-header icon="" :text="type=='checkshow' || type=='check'?'报名信息':'个人信息'"
                style="margin-bottom: 10px; border: 0px; margin-top: 15px">
              </lx-header>
              <div>
                <el-descriptions class="margin-top" :column="2" border>
                  <!-- 学员字段表  -->
                  <el-descriptions-item v-for="item in selectFormList" :span="item.span?item.span:1">
                    <template slot="label">
                      {{item.name}}
                    </template>
                    <div v-if="item.field==='company_date'">
                      {{student_info[item.field]?(student_info[item.field]=='0000-00-00'?'':student_info[item.field]):''}}
                    </div>
                    <div v-else>
                      {{student_info[item.field]?student_info[item.field]:''}}
                      <!-- 是否有更改的字段 -->
                      <template v-if="change_data.length>0">
                        <template v-for="change in change_data">
                          <span style="color:red"
                            v-if="change[item.field] && change['need_update']">-->{{change[item.field]}}</span>
                        </template>
                      </template>
                    </div>
                  </el-descriptions-item>
                  <el-descriptions-item :span="2" v-if="type==='check' || type==='checkshow' || type==='setPosition'">
                    <template slot="label">
                      本班职务
                    </template>
                    {{sign_result.position?sign_result.position:''}}
                  </el-descriptions-item>
                  <!-- 报名信息 -->
                  <template v-if="sign_info.length>0">
                    <!-- <lx-header v-if="type==='check' || type==='checkshow' || type==='setPosition'" icon="" text="报名信息"
                      style="margin-bottom: 10px; border: 0px; margin-top: 15px">
                    </lx-header> -->
                    <template v-if="type==='check' || type==='checkshow' || type==='setPosition'">
                      <!-- <el-descriptions class="margin-top" :column="2" border> -->
                      <template v-for="item in sign_info">
                        <el-descriptions-item :span="2" v-if="item.submit_files && item.submit_files.length>0">
                          <template slot="label">
                            {{item.name}}
                          </template>
                          <div>
                            <template v-for="file in item.submit_files">
                              <img style="width:100px;margin:10px" :src="host+file"></img>
                            </template>
                          </div>
                        </el-descriptions-item>
                        <el-descriptions-item v-else :span="2">
                          <template slot="label">
                            {{item.name}}
                          </template>
                          {{item.value}}
                        </el-descriptions-item>
                      </template>


                      <!-- </el-descriptions> -->
                    </template>
                  </template>
                </el-descriptions>

              </div>


              <!-- 审核查看 -->
              <lx-header v-if="type=='checkshow' || type=='check'" icon="" text="审核结果"
                style="margin-bottom: 10px; border: 0px; margin-top: 15px">
              </lx-header>

              <div v-if="type=='checkshow'">
                <div class="studentInfo">
                  <div>
                    <span>审核结果：</span>
                    <span v-for="item in apply_status_list">
                      <el-tag :type="item.type" v-if="sign_result.status===item.id">{{item.value}}</el-tag>
                    </span>
                  </div>
                  <div>
                    <span>评分：</span>
                    <span>{{sign_result.score}}</span>
                  </div>
                  <div v-if="sign_result.status===5">
                    <span>放弃原因：</span>
                    <span>{{sign_result.giveup_reason}}</span>
                  </div>
                  <div style="display: flex;" v-if="sign_result.status===1">
                    <span>录取通知书：</span>
                    <div>
                      <div v-for="item in sign_result.files">
                        <a :href="item.url" target="_blank" style="color:#0077CC">{{item.original_name}}</a>
                      </div>
                    </div>

                  </div>
                  <div>
                    <span>备注：</span>
                    <span>{{sign_result.reason?sign_result.reason:''}}</span>
                  </div>
                </div>
              </div>

            </div>
          </div>
        </div>
      </template>
      <!-- 审核 -->
      <template v-slot:status v-if="type=='check'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>审核：
          </div>
          <div class="xy-table-item-content">
            <el-select v-model="form.status" placeholder="请选择">
              <el-option v-for="item in apply_status_list" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:score v-if="type=='check'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>评分：
          </div>
          <div class="xy-table-item-content">
            <el-input type="number" v-model="form.score" placeholder="请输入评分"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:giveup_reason v-if="type=='check'&& form.status===5">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>放弃原因：
          </div>
          <div class="xy-table-item-content">
            <el-input type="textarea" v-model="form.giveup_reason" placeholder="请输入放弃原因"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:file_ids v-if="type=='check' && form.status===1">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>录取通知书：
          </div>
          <div class="xy-table-item-content">
            <el-upload :action="action" class='upload-demo' :file-list="fileList" ref="pictureUpload"
              :auto-upload="true" accept=".pdf" :limit="1" :on-success="uploadSuccess" :on-remove="uploadRemove">
              <el-button size="small" type="primary">点击上传</el-button>
              <div class="el-upload__tip" slot="tip">只能上传pdf文件</div>
            </el-upload>
          </div>
        </div>
      </template>
      <template v-slot:reason v-if="type=='check'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>备注：
          </div>
          <div class="xy-table-item-content">
            <el-input type="textarea" v-model="form.reason" placeholder="请输入备注(展示给学员查看)"></el-input>
          </div>
        </div>
      </template>
      <!-- 设置班委 -->
      <template v-slot:position v-if="type=='setPosition'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: bold;padding-right: 4px;"></span>班委名称：
          </div>
          <div class="xy-table-item-content">
            <el-input type="text" v-model="form.position" placeholder="请输入班委名称(如:班长)"></el-input>
          </div>
        </div>
      </template>


      <template v-slot:footerContent>
        <el-button type="primary" style='margin-left:5px;margin-bottom:5px;' v-if="type=='check' || type=='setPosition'"
          @click="submit">确认</el-button>
        <el-button type="primary" plain style='margin-left:5px;margin-bottom:5px;'
          v-else-if="type=='check'|| type=='setPosition'" @click="isShow=false">取消</el-button>
        <el-button type="primary" plain style='margin-left:5px;margin-bottom:5px;'
          v-else-if="type=='show'||type=='checkshow'" @click="isShow=false">关闭</el-button>
      </template>
    </xy-dialog>

    <!-- 选择要覆盖的 字段 -->
    <Modal v-model="showChange" width="60" title="审核并更新字段">
      <div class="update">
        <template v-for="item in selectFormList">
          <template v-for="(change,index) in change_data">
            <div class="update-item" v-if="change[item.field] && change['need_update']">
              <el-checkbox @change="(e)=>{changeCheckBox(e,index)}" v-model="change['is_checked']">
                <div class="update-item-name">{{item.name}}:</div>
                <div class="update-item-fieldwrap">
                  <div class="update-item-field" :style="{'margin-top':student_info[item.field]?'10px':'0px'}">
                    {{student_info[item.field]}}
                  </div>
                  <div class="update-item-field1" :style="{'margin-top':change[item.field]?'10px':'0px'}">
                    {{change[item.field]}}
                  </div>
                </div>
              </el-checkbox>
            </div>
          </template>
        </template>
      </div>
      <template v-slot:footer>
        <el-button plain type="primary" plain style='margin-left:5px;margin-bottom:5px;'
          @click="showChange = false">取消</el-button>
        <el-button type="primary" style='margin-left:5px;margin-bottom:5px;' @click="saveAndUpdate(false)">直接审核</el-button>
        <el-button type="primary" style='margin-left:5px;margin-bottom:5px;' @click="saveAndUpdate(true)">审核并更新</el-button>
      </template>
    </Modal>

  </div>
</template>

<script>
  import {
    show,
    save as saveUser
  } from '@/api/student/index.js'
  import {
    save,
    show as showSign
  } from '@/api/apply/index.js'


  import myMixins from "@/mixin/selectMixin.js";
  import formMixin from "@/mixin/formMixin.js";
  export default {
    mixins: [myMixins, formMixin],
    components: {

    },
    data() {
      return {
        isShow: false,
        type: 'show',
        typeName: '查看个人明细',
        showChange: false,
        id: '',
        action: `${process.env.VUE_APP_UPLOAD_API}`,
        host: `${process.env.VUE_APP_BASE_API}`,
        subjectObj: {},
        student_info: {},
        row: {},
        sign_info: [], //报名的信息，是去除 user表字段的其他字段
        change_data: [], // 有变更的user表中的字段 ，提交上来的一定是user表中的字段
        sign_result: {},
        update_student_info: {}, //存储需要更新的学员字段
        fileList: [],
        form: {
          show: '',
          status: 0,
          score: '',
          giveup_reason: '',
          file_ids: [],
          reason: '',
          position: ''
        },
      }
    },
    created() {},
    methods: {
      uploadSuccess(response, file, fileList) {
        this.fileList = fileList
      },
      uploadRemove(file, fileList) {
        this.fileList = fileList
      },
      changeCheckBox(e, index) {
        console.log(e, index)

        this.$nextTick(() => {
          this.$set(this.change_data[index], 'is_checked', e)
        })
        this.$forceUpdate()
        console.log("this.change", this.change_data)
      },
      // beforeUpload(file) {
      //   const isImage = file.type.includes('image');
      //   if (!isImage) {
      //     this.$message.error('请上传正确的图片格式文件');
      //   }
      //   return isImage && isLt2M;
      // },
      submit() {
        if (this.id) {
          this.form.id = this.id
        }
        let _arr = []
        if (this.fileList.length > 0) {
          this.fileList.map(item => {
            if (item.response) {
              _arr.push(item.response.id)
            } else {
              _arr.push(item.id)
            }
          })
        }
        this.form.file_ids = _arr

        // 如果是审核通过 提交的时候看下change_data有没有值 有的话要提醒是否覆盖user
        // 还要判断下 student_info中是否还有值与change_data中不一致的 才显示提醒，如果全部都更新过了值一样就不用了
        // 且选择的状态为审核通过 1
        let has_count = 0 // 是否还有字段值不一样
        if (this.type === 'check') {
          if (this.change_data.length > 0 && this.form.status === 1) {
            for (var k of this.change_data) {
              if (k['need_update']) {
                has_count++
              }
            }
            if (has_count > 0) {
              console.log("has_count", has_count, this.change_data)
              this.showChange = true
              return
            }
          }
        }

        console.log("123")
        // return
        // 其他的正常更新提交
        save({
          ...this.row,
          status: this.form.status,
          reason: this.form.reason,
          score: this.form.score,
          giveup_reason: this.form.giveup_reason,
          file_ids: this.form.file_ids,
          position: this.form.position
        }).then(res => {
          this.$message({
            type: 'success',
            message: this.type === 'check' ? '审核成功' : '设置成功'
          })
          this.isShow = false
          this.$emit('refresh')
        })
      },
      // 提交审核并更新用户信息
      saveAndUpdate(isUpdate) {
        console.log("isUpdate",isUpdate)
        // return
        if(isUpdate){
          let update_count = 0 // 需要更新的字段
          this.change_data.map(item => {
            if (item.is_checked) {
              update_count++
              // 替换学员数据中的值
              for (var student in this.student_info) {
                if (item[student]) {
                  this.update_student_info[student] = item[student]
                }
              }
            }
          })
          // 有需要更新的字段
          if (update_count > 0) {
            save({
              ...this.row,
              status: this.form.status,
              reason: this.form.reason,
              score: this.form.score,
              giveup_reason: this.form.giveup_reason,
              file_ids: this.form.file_ids,
              position: this.form.position
            }).then(res => {
              saveUser({
                ...this.update_student_info
              }).then(res => {
                this.$message({
                  type: 'success',
                  message: '审核并更新成功'
                })
                this.isShow = false
                this.showChange = false
                this.$emit('refresh')
              })

            })

            console.log("update", this.update_student_info)
          } else {
            this.$Message.warning("请选择需要更新的字段")
            return
          }
        }else{
          save({
            ...this.row,
            status: this.form.status,
            reason: this.form.reason,
            score: this.form.score,
            giveup_reason: this.form.giveup_reason,
            file_ids: this.form.file_ids,
            position: this.form.position
          }).then(res => {
            this.$message({
              type: 'success',
              message: '审核成功'
            })
            this.isShow = false
            this.showChange = false
            this.$emit('refresh')
          })
        }

      },

      getDetail() {
        show({
          id: this.id,
        }).then(res => {
          this.student_info = res
        })
      },
      getSignDetail() {
        showSign({
          id: this.id,
          show_relation: ['user']
        }).then(res => {
          this.student_info = res.user
          this.update_student_info = this.base.deepCopy(res.user)
          this.sign_result = res
          this.form.position = res.position ? res.position : ''
          this.change_data = res.change_data ? res.change_data : []

          // 提取出 自定义表单中不属于user的字段
          let _arr = []
          if (res.data && Array.isArray(res.data)) {
            res.data.map(item => {
              if (item.edit_input === 'files') {
                if (!this.base.isNull(item.value) && item.value.indexOf("/storage/files/") !== -1) {
                  item.submit_files = item.value.split(",")
                }
              }
              // 处理自定义字段中是否 是个人用户信息
              if (!this.student_info.hasOwnProperty(item.field)) {
                console.log("item.field")
                _arr.push(item)
              }
            })
            this.sign_info = _arr
          } else {
            this.sign_info = []
          }
          this.form.status = res.status ? res.status : 0
          this.form.score = res.score ? res.score : ''
          this.form.reason = res.reason ? res.reason : ''
          this.form.giveup_reason = res.giveup_reason ? res.giveup_reason : ''
          this.fileList = res.files ? res.files : []

          // 只显示 change_data 中与user表中字段值不一样的
          if (this.change_data.length > 0) {
            for (var k of this.change_data) {
              for (var s in this.student_info) {
                console.log(k, s, k.hasOwnProperty(s), k[s] != this.student_info[s])
                if (k.hasOwnProperty(s) && k[s] != this.student_info[s]) {
                  k['need_update'] = true
                  k['is_checked'] = true
                }
              }
            }
          }
          console.log("this.sign_info", this.sign_info, this.change_data)
        })
      }
    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          if (this.type === 'show') {
            this.typeName = "查看个人明细"
            this.getDetail()
          } else if (this.type === 'check' || this.type === 'checkshow' || this.type === 'setPosition') {
            this.getSignDetail()
            if (this.type === 'check') {
              this.typeName = '审核'
            } else if (this.type === 'setPosition') {
              this.typeName = '设置班委'
            } else {
              this.typeName = '查看'
            }

          }
        } else {
          this.id = ''
          this.type = 'show'
          this.showChange = false
          this.subjectObj = {}
          this.sign_result = {}
          this.sign_info = []
          this.change_data = []
          this.fileList = []
          this.student_info = {}
          this.update_student_info = {}
          this.row = {}
          this.$refs['dialog'].reset()
        }
      },
    }

  }
</script>

<style scoped lang="scss">
  ::v-deep .show,
  ::v-deep .file_ids,
  ::v-deep .reason,
  ::v-deep .giveup_reason {
    flex-basis: 100%;
  }

  ::v-deep .el-descriptions-item__label {
    width: 15%;
  }

  ::v-deep .v-header {
    margin-top: 0 !important;
  }

  .update {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    padding: 30px;

    &-item {
      flex-basis: 50%;
      margin: 10px 0;
      font-size: 20px;

      ::v-deep .el-checkbox {
        display: flex;
        align-items: baseline;
      }

      &-fieldwrap {
        font-size: 16px;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
      }

      &-name {
        font-size: 16px;
        color: rgba(0, 0, 0, 0.5)
      }

      &-field {
        font-size: 16px;
        margin-top: 10px;
        flex-basis: 100%;
        color: #000
      }

      &-field1 {
        font-size: 16px;
        margin-top: 10px;
        flex-basis: 100%;
        color: red
      }
    }
  }

  .studentInfo {
    &>div {
      display: flex;

      &>div {
        width: 50%;

        span:first-child {
          display: inline-block;
          width: 160px;
          text-align: right;
        }
      }

      img {
        width: 80px;
        height: 80px;
      }
    }
  }

  .companyInfo {
    &>div {
      display: flex;

      span:first-child {
        display: inline-block;
        width: 160px;
        text-align: right;
      }
    }
  }
</style>
