<template>
  <el-dialog
    v-dialogDrag
    v-loading.fullscreen.lock="fullscreenLoading"
    :before-close="cancel"
    :title="dialogTitle"
    :visible.sync="dialogShowFlag"
    append-to-body
    width="500px"
  >
    <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="报废原因：">
              <el-input
                v-model="dynamicValidateForm.scrapReason"
                placeholder="请输入"
                size="small"
                style="width: 250px"
              ></el-input>
            </el-form-item>
            <el-form-item label="损坏原因：">
              <el-radio-group
                style="width: 250px"
                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: 250px"
                :file-list="fileList"
                :action-url="actionUrl"
                :limit="3"
                :multiple="true"
                @remove="handleRemove"
                @preview="handlePreview"
                @exceed="handleExceed"
                @before-remove="beforeRemove"
                @success="handleSuccess"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </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="报废原因：">
            <el-input
              v-model="dynamicValidateFormTwo.scrapReason"
              placeholder="请输入"
              size="small"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item label="损坏原因：">
            <el-radio-group
              style="width: 250px"
              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="报废数量："
            prop="scrapNum"
            :rules="{
              required: false,
              validator: numberIntegerValidator,
              trigger: 'blur',
            }"
          >
            <el-input
              v-model="dynamicValidateFormTwo.scrapNum"
              placeholder="请输入"
              size="small"
              style="width: 250px"
            ></el-input>
          </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: 250px"
              :file-list="fileList"
              :action-url="actionUrl"
              :limit="3"
              :multiple="true"
              @remove="handleRemove"
              @preview="handlePreview"
              @exceed="handleExceed"
              @before-remove="beforeRemove"
              @success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </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',
      // 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');
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    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)) {
        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,
            scrapNum: this.dynamicValidateFormTwo.scrapNum,
          }
          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;
        }
      });
    },
    fileListChange(data) {
      data.map(item => {
        this.fileIds = data.map(item => item.id).join(',');
      })
    },
    init() {
      if (this.rowObj.code !== null && this.rowObj.code !== '') {
        this.dynamicValidateForm = {};
        this.dynamicValidateFormTwo = {};
        this.isShow = false
      } else {
        this.dynamicValidateForm = {};
        this.dynamicValidateFormTwo = {};
        this.isShow = true
      }
      getInfo().then(res => {
        this.companyId = res.user.companyId
      })
      this.fileList = []
      this.fileIds = []

    },
    // 取消按钮
    cancel() {
      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;
}
</style>
