<template>
  <div class="page-dialog">
    <block-header :title="title">
      <el-button type="primary" @click="changeRiskLevel" size="small">调整风险等级</el-button>
    </block-header>
    <el-table border size="mini" :highlight-current-row="true" :header-row-class-name="headerStyle" :data="data" stripe
      style="width: 100%;">
      <el-table-column align="center" prop="clientName" label="姓名"></el-table-column>
      <el-table-column align="center" prop="riskGmtCreated" :formatter="dateFormats" label="修改日期"></el-table-column>
      <el-table-column align="center" prop="creator" label="操作人"></el-table-column>
      <el-table-column align="center" prop="riskType" label="风险等级"></el-table-column>
      <el-table-column align="center" prop="riskLifted" :formatter="dateFormats" label="自定义解除日期"></el-table-column>
      <el-table-column align="center" prop="riskContent" label="风险描述"></el-table-column>
      <el-table-column align="center" prop="riskImageUrl" label="资料">
        <template slot-scope="scope">
          <template v-if="scope.row.riskImageUrl && scope.row.riskImageUrl !== null">
            <template v-for="item in scope.row.riskImageUrl">
              <el-image style="width: 50px; height: 50px; margin: 0 5px; cursor: pointer;" fit="fill"
                :preview-src-list="scope.row.riskImageUrl" :src="item"></el-image>
            </template>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 调整风险等级弹框 -->
    <template v-if="visible">
      <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="调整风险等级" width="35%"
        :visible.sync="visible" :before-close="handleCancel">
        <div>
          <div class="box-agreement">
            <el-form label-suffix=":" :rules="rules" label-width="130px" label-position="right" :model="riskForm"
              ref="form">
              <el-row>
                <el-col :span="24">
                  <el-form-item prop="riskType" label="风险等级">
                    <el-select v-model="riskForm.riskType" size="small" placeholder="请选择风险等级">
                      <el-option v-for="item in this.$enumUtils.toValue('RiskLevelEnum')" :key="item.value"
                        :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </el-form-item>

                  <template
                    v-if="riskForm.riskType === 'R1' || riskForm.riskType === 'R2' || riskForm.riskType === 'R3' || riskForm.riskType === 'RP1'">

                    <el-form-item prop="isRetract" label="是否自定义解除">
                      <el-radio-group v-model="riskForm.isRetract">
                        <el-radio label="1">是</el-radio>
                        <el-radio label="0">否</el-radio>
                      </el-radio-group>
                    </el-form-item>

                    <el-form-item v-if="riskForm.isRetract === '1'" prop="riskLifted" label="自定义解除日期">
                      <el-date-picker size="small" v-model="riskForm.riskLifted" type="date" placeholder="选择日期">
                      </el-date-picker>
                    </el-form-item>

                  </template>


                  <el-form-item prop="riskContent" label="风险描述">
                    <el-input type="textarea" :row="4" placeholder="请输入风险描述" v-model="riskForm.riskContent"></el-input>
                  </el-form-item>


                  <el-form-item prop="riskImages" label="资料">
                    <el-upload :file-list="fileList" class="upload-demo" list-type="picture-card" :action="oss.action"
                      :data="oss.data" :multiple="oss.multiple" accept=".jpeg,.jpg,.png"
                      :http-request="uploadSectionFile" :before-upload="handleBeforeApplyUpload"
                      :on-remove="handleLoanApplyRemove">
                      <i class="el-icon-plus"></i>
                    </el-upload>
                  </el-form-item>

                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="handleCancel">取 消</el-button>
          <el-button size="small" type="primary" @click="onSubmit">提 交</el-button>
        </div>
      </el-dialog>
    </template>

  </div>
</template>

<script>
import Axios from 'axios'
import * as moment from "moment";
export default {
  name: 'RiskInfo',
  props: {
    dialogVisible: {
      type: Boolean,
      required: true,
    },
    title: {
      type: String,
      required: true,
    },
    params: {
      type: Object,
      required: true
    },
  },
  data() {
    return {
      form: {
        current: 1,
        size: 1000,
        riskType: "",
        certNo: "",
        endDate: "",
        startDate: ""
      },
      data: [],
      fileList: [],
      oss: {
        action: '',
        data: {},
        multiple: true,
      },
      file: null,
      visible: false,
      rules: {
        riskType: [
          { required: true, message: "请选择风险等级", trigger: 'change' }
        ],
        riskContent: [
          { required: true, message: "请输入", trigger: 'blur' }
        ],
        riskLifted: [
          { required: true, message: "请选择解除日期", trigger: 'blur' }
        ],
        isRetract: [
          { required: true, message: "请选择是否解除", trigger: 'change' }
        ]
      },
      riskForm: {
        riskType: "",
        riskLifted: "",
        isRetract: "",
        riskImageUrl: null,
        riskContent: '',

        certNo: '',
        clientName: '',
        clientPhone: '',

        creator: localStorage.getItem("userName"),
      }
    }
  },
  async created() {
    const params = this.params;
    console.log(params, '传的值')
    this.form.certNo = params.idCard;
    this.riskForm.certNo = params.idCard;
    this.riskForm.clientName = params.clientName;
    this.riskForm.clientPhone = params.clientCell;

    await this.init()
  },
  methods: {
    headerStyle() {
      return "tableHeaderStyle";
    },
    async init() {
      const res = await this.$$post('/risk/getRiskLogPage', this.form);
      const { success, result } = res.data;
      if (success && result !== null) {
        this.data = result.records;
      }
    },
    /*日期*/
    dateFormats: function (row, column) {
      let date = row[column.property]
      if (!date || date === undefined) {
        return ''
      }
      return moment(date).format("YYYY-MM-DD")
    },
    handleClose() {
      this.$emit("handleClose");
    },
    /** 风险等级调整弹框显示 */
    changeRiskLevel() {
      this.visible = true
    },
    /** 风险等级调整表单取消 */
    handleCancel() {
      this.fileList = []
      this.$refs['form'].resetFields()
      this.visible = false
    },
    /** 风险等级调整表单提交 */
    onSubmit() {
      console.log(this.fileList, '文件列表');
      const feedVoucher = [];
      this.fileList.forEach(item => {
        feedVoucher.push(item.url);
      })

      this.riskForm.riskImageUrl = feedVoucher
      this.$refs['form'].validate(async (valid) => {
        if (!valid) {
          return false
        }

        this.$confirm('确认要提交吗？').then(async _ => {
          const res = await this.$$post('/risk/insertRiskLogBack', { ...this.riskForm })
          if (res.data.success) {
            this.$message({ message: '操作成功', type: 'success' });
            this.handleCancel()
            await this.init()
          } else {
            this.$message({ message: res.data.message, type: 'error' });
          }
        }).catch(_ => {});
      });
    },

    handleBeforeApplyUpload(file) {
      const attachType = 'LOESS_TRANSFER_APPLY';
      return this.$$get(`/oss/signature/?fileType=` + attachType + "&fileName=" + file.name).then(res => {
        if (res.data.code !== '200') {
          this.$message.error(res.data.message);
          return false
        }
        const result = res.data.result.result;
        const data = {};
        const tempOss = {};
        data.OSSAccessKeyId = result.accessId;
        data.policy = result.policy;
        data.Signature = result.signature;
        data.key = result.dir;
        tempOss.action = result.host;
        tempOss.data = data;
        this.oss = tempOss;
      });
    },


    uploadSectionFile(params) {
      const { action, data } = this.oss
      console.log(params, '图片信息')
      const d = new FormData();
      d.append("key", data.key);
      d.append("policy", data.policy);
      d.append("OSSAccessKeyId", data.OSSAccessKeyId);
      d.append("success_action_status", "200");
      d.append("Signature", data.Signature);
      d.append("file", params.file);
      const baseUrl = action;


      Axios({
        url: baseUrl,
        method: 'post',
        data: d,
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then((res) => {
        if (res.status === 200) {
          const imgUrl = `${baseUrl}/${data.key}`;
          this.$notify({ title: '成功', message: params.file.name + ",上传成功", type: 'success' });
          this.fileList.push({
            name: params.file.name,
            url: imgUrl
          })
        }
      }).catch((e) => {
        console.log(e, '错误')
      });
    },


    handleLoanApplyRemove(file, fileList) {
      const { name } = file;
      console.log(file, 'r2')
      console.log(fileList, 'r3')
      const i1 = this.fileList.findIndex((item) => item.name === name)
      if (i1 !== -1) {
        this.fileList.splice(i1, 1)
      }
    },
  }
}
</script>

<style></style>
