<template>
  <div class="page-byh-service">
    <block-header title="搜索"/>
    <div class="page-search">
      <el-form size="small" label-suffix=":" :inline="true" label-width="80px" ref="refForm" :model="form"
               class="demo-form-inline">
        <el-form-item prop="loanNo" label="借款编号">
          <el-input
              clearable
              v-model.trim="form.loanNo"
              @keyup.enter.native="onSubmit"
              placeholder="请输入"></el-input>
        </el-form-item>

        <template v-if="EnumList.length">
          <el-form-item prop="protocolType" label="协议类型">
            <el-select clearable v-model="form.protocolType" clearable placeholder="请选择产品">
              <el-option
                  v-for="item in EnumList"
                  :key="item.protocolType"
                  :label="item.protocolTypeName"
                  :value="item.protocolType"></el-option>
            </el-select>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="onReset('refForm')">清空</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表 -->

    <block-header title="协议列表">
      <el-button type="primary" @click="handleCreateAgreement" icon="el-icon-plus" size="small">生成协议</el-button>
    </block-header>
    <div class="p-table">
      <el-table border
                :highlight-current-row="true"
                :header-row-class-name="headerStyle" size="small" :data="list" stripe style="width: 100%;">
        <el-table-column align="center" prop="tempName" label="模板名称"></el-table-column>
        <el-table-column align="center" prop="protocolTypeName" label="协议类型"></el-table-column>
        <el-table-column align="center" width="80" prop="clientName" label="客户姓名"></el-table-column>
        <el-table-column align="center" prop="loanNo" label="借款编号"></el-table-column>
        <el-table-column align="center" label="协议模板">
          <template slot-scope="scope">
            <span v-if="!scope.row.templateResponseList">无</span>
            <ul v-else>
              <li v-for="(item,index) in scope.row.templateResponseList" :key="index">
                <a class="link-active" :href="item.templateUrl"
                   target="_blank">{{ item.templateName }}({{ item.isSign === 'true' ? '已签署' : '未签署' }})</a>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column align="center" label="承诺书">
          <template slot-scope="scope">
            <span v-if="!scope.row.realTemplateResponse">无</span>
            <div v-else>
              <a v-if="scope.row.realTemplateResponse.isSign==='true'" class="link-active"
                 :href="scope.row.realTemplateResponse.templateUrl" target="_blank">已签署</a>
              <a v-else :href="scope.row.realTemplateResponse.templateUrl" class="link-null" target="_blank">未签署</a>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="80" label="签署地址">
          <template slot-scope="scope">
            <a target="_blank" :href="H5+'#/login?loanNo='+scope.row.tempId+'&id='+scope.row.id">点击预览</a>
          </template>
        </el-table-column>
        <el-table-column align="center" label="附件">
          <template slot-scope="scope">
            <div v-if="!scope.row.annexUrl">无</div>
            <div class="display:flex;" v-else>
              <template v-for="item in scope.row.annexUrl">
                <el-image
                    v-if="item.indexOf('.jpg')!==-1"
                    :key="item"
                    :preview-src-list="scope.row.imgs"
                    style="width: 50px; height: 50px;margin: 0 8px 8px 8px"
                    :src="item"
                    fit="contain"></el-image>
                <div v-else>
                  <video :key="item" @click="handlePreviewVideo(item)" style="width:50px;height:50px;object-fit:fill;"
                         :src="item"/>
                </div>
              </template>

            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="statusStr" label="状态"></el-table-column>
        <el-table-column align="center" width="90" prop="gmtCreated" :formatter="transDateFormat"
                         label="创建时间"></el-table-column>
        <el-table-column align="center" width="90" prop="urlEffectiveTime" :formatter="transDateFormat"
                         label="有效时间"></el-table-column>
        <el-table-column align="center" width="90" prop="urlEffectiveStr"
                         label="链接状态">
          <template slot-scope="scope">
            <div v-if="scope.row.urlEffectiveStr==='true'">链接有效</div>
            <div v-else>链接过期</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-if="scope.row.invalid==='true'" slot-scope="scope">
            <el-button type="text" size="small" @click="handleCancel(scope.row)">协议作废</el-button>
            <el-button type="text" size="small" @click="handleDelay(scope.row)">延时</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pages">
      <el-pagination
          background
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page.sync="form.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="form.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>
    </div>


    <!-- 生成协议弹框 -->
    <template v-if="SignVisible">
      <CreateAgreement
          :enum-list="EnumList"
          :dialog-visible="SignVisible"
          @handleCallback="init"
          @handleClose="SignVisible = false"/>
    </template>

    <!-- 延时弹框 -->
    <template v-if="delayVisible">
      <el-dialog title="链接有效期延时" width="35%" :visible.sync="delayVisible">
        <el-form label-suffix=":" label-width="110px" :rules="delayRules" :model="delayForm">
          <el-form-item prop="effectiveTime" label="延期时间">
            <el-date-picker v-model="delayForm.effectiveTime" type="datetime" :picker-options="pickerOptions"
                            value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="delayVisible = false">取 消</el-button>
          <el-button type="primary" @click="delaySubmit">确 定</el-button>
        </div>
      </el-dialog>
    </template>

    <el-dialog width="45%" title="视频预览" :visible.sync="showvideoplay" v-model="showvideoplay">
      <video
          controls
          preload="auto"
          style="width:100%;height:400px;object-fit: contain;"
          :src="videourl"
          v-if="videourl"
      ></video>
    </el-dialog>

  </div>
</template>

<script>
import CreateAgreement from "./com/CreateAgreement";

export default {
  name: "SignAgreement",
  components: {
    CreateAgreement
  },
  data() {
    return {
      showvideoplay: false,
      videourl: '',
      H5: process.env.VUE_APP_SIGN_URL,


      delayVisible: false,
      SignVisible: false,
      EnumList: [],
      total: 1,
      list: [],
      delayRules: {
        effectiveTime: [
          {required: true, message: "请选择时间", trigger: 'blur'}
        ],
      },
      form: {
        "current": 1,
        "size": 10,
        "loanNo": "",
        "protocolType": ""
      },

      delayItem: null,
      delayForm: {
        clientNo: "",
        loanNo: "",
        protocolType: "",
        effectiveTime: '',
        id:''
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
        selectableRange: "00:00:00 - 23:59:59",
      }
    }
  },
  created() {
    // 初始化协议枚举
    this.initAgreementEnum();
    // 初始化列表
    this.init();
  },

  methods: {
    /** 表格样式 */
    headerStyle() {
      return "tableHeaderStyle";
    },

    /** 生成协议 */
    handleCreateAgreement() {
      this.SignVisible = true;
    },

    /** 初始化协议列表 **/
    async init() {
      try {
        const params = this.form
        const form = Object.assign({}, params)
        const res = await this.$$post('/protocol/selectProtocolList', {...form})
        if (res.status === 200 && res.data.success) {
          const {data, total} = res.data.result

          data.forEach(item => {
            const imgs = []
            if (item.annexUrl !== null) {
              item.annexUrl.forEach(img => {
                if (img.indexOf('mp4') === -1) {
                  imgs.push(img)
                }
              })
              item.imgs = imgs
            }
          })

          this.list = data;
          this.total = total
        } else {
          this.$message.error(res.data.message);
        }
      } catch (err) {
        this.$Message.error(err || '系统异常');
        console.log(err, '初始化协议列表错误')
      }
    },

    /** 初始化协议枚举列表*/
    async initAgreementEnum() {
      try {
        const res = await this.$$get('/protocol/selectProtocolEnumList')
        if (res.status === 200 && res.data.success) {
          this.EnumList = res.data.result;
        } else {
          this.$message.error(res.data.message);
        }
      } catch (err) {
        this.$message.error(res || '初始化协议枚举列表报错');
      }
    },
    /** 协议作废 */
    async handleCancel(row) {
      // 加个确认弹框
      this.$confirm("是否确认作废协议?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "primary",
      }).then(async () => {
        try {
          const {clientNo, loanNo,id} = row
          const params = {clientNo, loanNo,id}
          const res = await this.$$post('/protocol/cancelProtocol', {...params})
          if (res.status === 200 && res.data.success) {
            this.$message.success('操作成功！');
            await this.init()
          } else {
            this.$message.error(res.data.message);
          }
        } catch (err) {
          this.$message.error(res || '初始化协议枚举列表报错');
        }
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消",
        });
      });
    },

    /** 延期弹框 */
    handleDelay(row) {
      const {loanNo, clientNo, protocolType,id} = row;
      this.delayForm.loanNo = loanNo;
      this.delayForm.clientNo = clientNo;
      this.delayForm.protocolType = protocolType;
      this.delayForm.id = id;
      this.delayVisible = true;
    },
    /** 延期提交 */
    async delaySubmit() {
      try {
        const form = this.delayForm
        const res = await this.$$post('/protocol/urlDelayed', {...form})
        if (res.status === 200 && res.data.success) {
          this.$message.success('操作成功！');
          await this.init()
          this.delayVisible = false;
        } else {
          this.$message.error(res.data.message);
        }
      } catch (err) {
        this.$message.error(res || '延期失败');
      }
    },
    /** 搜索提交 */
    onSubmit() {
      this.init()
    },

    handleCurrentChange(e) {
      this.form.current = e;
      this.init();
    },
    handleSizeChange(e) {
      this.form.size = e;
      this.form.current = 1;
      this.init();
    },

    /** 预览大图 */
    handlePreview(item, list) {
      const cache = []
      list.forEach(item => {
        console.log(item, '==')
        if (item.indexOf('mp4') === -1) {
          cache.push(item)
        }
      })
    },

    /** 视频预览 */
    handlePreviewVideo(item) {
      console.log(item, 'nasha')
      this.showvideoplay = true;
      this.videourl = item;
    }

  }
}


</script>

<style scoped>
.link-active, .link-null {
  text-decoration: none;
}

.link-active {
  color: #155bd4;
}

ul, li {
  list-style: none;
  margin: 0;
  padding: 0;
}

.p-table {
  margin-bottom: 20px;
}

.pages {
  display: flex;
  align-items: center;
  justify-content: center;
}

</style>
