<template>
  <el-dialog
    v-dialogDrag
    v-loading.fullscreen.lock="fullscreenLoading"
    :before-close="cancel"
    :title="dialogTitle"
    :visible.sync="dialogShowFlag"
    append-to-body
    width="600px"
  >
    <div class="form_box_one" v-if="!isShow">
      <el-form ref="dynamicValidateForm" :model="dynamicValidateForm" class="demo-dynamic" label-width="100px">
        <div class="bor_box">
          <p class="form_box_title">编码管理设备</p>
          <div class="form_box_line"></div>
          <div class="form_box_item">
            <el-form-item label="报废原因：" prop="scrapReason" :rules="{ required: true, message: '请输入报废原因', trigger: 'blur'}">
              <el-input
                v-model="dynamicValidateForm.scrapReason"
                placeholder="请输入"
                size="small"
                maxlength="50"
                style="width: 350px"
              ></el-input>
            </el-form-item>
            <el-form-item label="损坏原因：">
              <el-radio-group style="width: 350px" v-model="dynamicValidateForm.scrapType">
                <el-radio :label="1">人为</el-radio>
                <el-radio :label="0">自然</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="损坏照片：">
              <!-- <uploadImage
                style="width: 250px"
                :value="fileList"
                :limit="limit"
                :fileSize="fileSize"
                :fileType="fileType"
                :isShowTip="isShowTip"
                @fileListChange="fileListChange"
              ></uploadImage> -->
              <upload
                style="width: 350px"
                :file-list="fileList"
                :action-url="actionUrl"
                :limit="3"
                :multiple="true"
                @remove="handleRemove"
                @preview="handlePreview"
                @before-remove="beforeRemove"
                @success="handleSuccess"
              >
                <template>
                  <el-row class="upload-tip">
                    <el-button size="small" type="primary">点击上传</el-button>
                  </el-row>
                  <el-row class="upload-tip">
                    <span class="tip-text">请上传jpg、jpeg、png格式的图片，单张图片大小不可超过5M，最多可上传3张</span>
                  </el-row>
                </template>
              </upload>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </div>
    </div>
    <div class="form_box_two" v-if="isShow">
      <el-form ref="dynamicValidateFormTwo" :model="dynamicValidateFormTwo" class="demo-dynamic" label-width="100px">
        <p class="form_box_title">数量管理设备</p>
        <div class="form_box_line"></div>
        <div class="form_box_item">
          <el-form-item
            label="报废数量："
            prop="scrapNum"
            :rules="{
              required: true,
              validator: numberIntegerValidator,
              trigger: 'blur',
            }"
          >
            <el-input
              v-model="dynamicValidateFormTwo.scrapNum"
              placeholder="请输入"
              size="small"
              maxlength="10"
              style="width: 350px"
            ></el-input>
          </el-form-item>
          <el-form-item label="报废原因：" prop="scrapReason" :rules="{ required: true, message: '请输入报废原因', trigger: 'blur'}">
            <el-input
              v-model="dynamicValidateFormTwo.scrapReason"
              placeholder="请输入"
              size="small"
              maxlength="50"
              style="width: 350px"
            ></el-input>
          </el-form-item>
          <el-form-item label="损坏原因：">
            <el-radio-group style="width: 350px" v-model="dynamicValidateFormTwo.scrapType">
              <el-radio :label="1">人为</el-radio>
              <el-radio :label="0">自然</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="损坏照片：">
            <!-- <uploadImage
              style="width: 250px"
              :value="fileList"
              :limit="limit"
              :fileSize="fileSize"
              :fileType="fileType"
              :isShowTip="isShowTip"
              @fileListChange="fileListChange"
            ></uploadImage> -->
            <upload
              style="width: 350px"
              :file-list="fileList"
              :action-url="actionUrl"
              :limit="3"
              :multiple="true"
              @remove="handleRemove"
              @preview="handlePreview"
              @before-remove="beforeRemove"
              @success="handleSuccess"
            >
              <template>
                <el-row class="upload-tip">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-row>
                <el-row class="upload-tip">
                  <span class="tip-text">请上传jpg、jpeg、png格式的图片，单张图片大小不可超过5M，最多可上传3张</span>
                </el-row>
              </template>
            </upload>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitTwo">保存</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import uploadImage from './uploadImage.vue'
import upload from './upload.vue'
import { submitRepairApplyApi, getRepairMaTypeListApi } from '@/api/repairTest/repair'
import { getInfo } from '@/api/login'
export default {
  components: {
    uploadImage,
    upload,
  },
  props: {
    // 弹窗是否显示
    isShowFlag: {
      type: Boolean,
      default: false,
    },
    // 对应操作数据键值
    priKey: {
      type: [String, Number],
      default: '',
    },
    //弹窗标题
    dialogTitle: {
      type: String,
      default: '',
    },
    rowObj: {
      type: Object,
      default: {},
    },
  },
  watch: {
    isShowFlag(val) {
      if (val) {
        this.init()
      }
    },
  },
  computed: {
    dialogShowFlag: {
      get() {
        return this.isShowFlag
      },
      set(v) {
        this.$emit('update:isShowFlag', v)
      },
    },
  },
  data() {
    return {
      // actionUrl: process.env.VUE_APP_BASE_API + '/sgzb-system/sys/file/upload',
      actionUrl: process.env.VUE_APP_BASE_API + '/system/sys/file/upload',
      // uploadTip: '只能上传jpg/png文件，且不超过500kb',
      fileIds: [],
      fileList: [],
      limit: 3,
      fileSize: 5,
      fileType: ['png', 'jpg', 'jpeg'],
      isShowTip: true,
      fullscreenLoading: false,
      dynamicValidateForm: {},
      dynamicValidateFormTwo: {},
      taskId: '',
      companyId: '',
      isShow: true,
    }
  },
  mounted() {
    this.$eventBus.$on('taskId', taskId => {
      this.taskId = taskId
    })
    getInfo().then(res => {
      this.companyId = res.user.companyId
    })
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = fileList
      console.log('fileListRemove', fileList)
      fileList.map(item => {
        this.fileIds = fileList.map(item => item.response.data.id).join(',')
      })
    },
    handlePreview(file) {
      console.log('file')
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(response, fileList) {
      this.fileList = fileList
      fileList.map(item => {
        this.fileIds = fileList.map(item => item.response.data.id).join(',')
      })
    },
    //正则校验配件数量--维修数量
    numberIntegerValidator(rule, value, callback) {
      const reg = /^\+?[1-9][0-9]*$/
      if ((value && reg.test(value)) && value <= this.rowObj.repairNum) {
        callback()
      } else {
        callback(new Error('请输入大于0并且小于维修总量的正整数'))
      }
    },
    getList() {
      let params = {
        taskId: this.taskId,
      }
      this.loading = true
      getRepairMaTypeListApi(params).then(res => {
        if (res.code == 200) {
          this.repairList = res.rows
          this.total = res.total
          this.loading = false
        }
      })
    },
    submit() {
      this.$refs['dynamicValidateForm'].validate(valid => {
        if (valid) {
          // 编码管理传递参数
          let params = {
            taskId: this.rowObj.taskId,
            maId: this.rowObj.maId,
            typeId: this.rowObj.typeId,
            id: this.rowObj.id,
            repairType: 3,
            companyId: this.companyId,
            scrapReason: this.dynamicValidateForm.scrapReason,
            scrapType: this.dynamicValidateForm.scrapType,
            fileIds: this.fileIds.length > 0 ? this.fileIds : '',
            scrapNum: 1,
          }
          this.fullscreenLoading = true
          submitRepairApplyApi(params)
            .then(res => {
              if (res.code == 200) {
                this.fileList = []
                this.fileIds = []
                this.getList()
                this.$message.success('操作成功!')
                this.fullscreenLoading = false
                this.dialogShowFlag = false
                this.$emit('domainChange', res.code)
              }
            })
            .catch(() => {
              this.fullscreenLoading = false
            })
        } else {
          return false
        }
      })
    },
    submitTwo() {
      this.$refs['dynamicValidateFormTwo'].validate(valid => {
        if (valid) {
          // 数量管理传递参数
          let params = {
            taskId: this.rowObj.taskId,
            maId: this.rowObj.maId,
            typeId: this.rowObj.typeId,
            id: this.rowObj.id,
            companyId: this.companyId,
            repairType: 3,
            companyId: this.companyId,
            scrapReason: this.dynamicValidateFormTwo.scrapReason,
            scrapType: this.dynamicValidateFormTwo.scrapType,
            fileIds: this.fileIds.length > 0 ? this.fileIds : '',
            scrapNum: this.dynamicValidateFormTwo.scrapNum,
          }
          this.fullscreenLoading = true
          submitRepairApplyApi(params)
            .then(res => {
              if (res.code == 200) {
                this.$refs.dynamicValidateFormTwo.clearValidate()
                this.fileList = []
                this.fileIds = []
                this.getList()
                this.$message.success('操作成功!')
                this.fullscreenLoading = false
                this.dialogShowFlag = false
                this.$emit('domainChange', res.code)
              }
            })
            .catch(() => {
              this.$refs.dynamicValidateFormTwo.clearValidate()
              this.fullscreenLoading = false
            })
        } else {
          return false
        }
      })
    },
    fileListChange(data) {
      data.map(item => {
        this.fileIds = data.map(item => item.id).join(',')
      })
    },
    init() {
      // 清除验证
      if (this.$refs.dynamicValidateForm) this.$refs.dynamicValidateForm.clearValidate()
      if (this.$refs.dynamicValidateFormTwo) this.$refs.dynamicValidateFormTwo.clearValidate()
      if (this.rowObj.code !== null && this.rowObj.code !== '') {
        this.dynamicValidateForm = {
          scrapReason: '',
          scrapType: 1,
        }
        this.dynamicValidateFormTwo = {
          scrapNum: '',
          scrapReason: '',
          scrapType: 1,
        }
        this.isShow = false
      } else {
        this.dynamicValidateForm = {
          scrapReason: '',
          scrapType: 1,
        }
        this.dynamicValidateFormTwo = {
          scrapNum: '',
          scrapReason: '',
          scrapType: 1,
        }
        this.isShow = true
      }
      getInfo().then(res => {
        this.companyId = res.user.companyId
      })
      this.fileList = []
      this.fileIds = []
    },
    // 取消按钮
    cancel() {
      // this.$refs.dynamicValidateFormTwo.clearValidate()
      this.dialogShowFlag = false
      this.fileList = []
    },
    addDomainOne() {
      this.dynamicValidateForm.premiumList.push({
        selected: 'N',
        premium: undefined,
        rate: undefined,
        feeRate: undefined,
        fee: undefined,
        baofei1_unit: '',
        shangyoufeiyonge_unit: '',
        downRate: undefined,
        downFee: undefined,
        xiayoufeiyonge_unit: '',
        key: Date.now(),
      })
    },
    addDomainTwo() {
      this.dynamicValidateForm.premiumListTwo.push({
        selected: 'N',
        premium: undefined,
        rate: undefined,
        feeRate: undefined,
        fee: undefined,
        baofei1_unit: '',
        shangyoufeiyonge_unit: '',
        downRate: undefined,
        downFee: undefined,
        xiayoufeiyonge_unit: '',
        key: Date.now(),
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.form_box_one {
  display: flex;
  flex-direction: column;

  .form_box_title {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    font-size: 12px;
  }

  .form_box_line {
    margin: 8px 0;
    width: 100%;
    border-bottom: 2px solid #1a1c22;
  }

  .form_box_item {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .add_box {
    display: flex;
    justify-content: flex-end;
    margin-right: 3%;
  }
}

.form_box_two {
  display: flex;
  flex-direction: column;

  .form_box_title {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    font-size: 12px;
  }

  .form_box_line {
    margin: 8px 0;
    width: 100%;
    border-bottom: 2px solid #1a1c22;
  }

  .form_box_item {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .add_box {
    display: flex;
    justify-content: flex-end;
    margin-right: 3%;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.upload-tip {
  text-align: left;

  .tip-text {
    font-size: 13px;
    color: red;
    letter-spacing: 1px;
  }
}
</style>
