<template>
  <div class="page-dialog">
    <block-header title="借款记录"></block-header>
    <div class="block-box">
      <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" width="140" prop="loanNo" label="借款编号"></el-table-column>
        <el-table-column align="center" prop="gmtCreated" label="申请日期" :formatter="dateFormats"></el-table-column>
        <el-table-column align="center" prop="startDate" label="放款日期" :formatter="dateFormats"></el-table-column>
        <el-table-column align="center" prop="raiseAmt" label="放款本金"></el-table-column>
        <el-table-column align="center" prop="productNameStr" label="产品名称"></el-table-column>

        <el-table-column align="center" prop="capitalCodeStr" label="放款资方"></el-table-column>
        <el-table-column align="center" prop="serviceThemeName" label="服务费主体"></el-table-column>
        <el-table-column align="center" prop="status" label="借款单状态">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status === 'AUDITED'" size="small">{{ loanStatusFormat(scope.row) }}
            </el-tag>
            <el-tag v-else-if="scope.row.status === 'SETTLED'" size="small">{{ loanStatusFormat(scope.row) }}</el-tag>
            <el-tag type="danger" v-else-if="scope.row.status === 'OVERDUED'" size="small">
              {{ loanStatusFormat(scope.row) }}
            </el-tag>
            <el-tag type="warning" v-else-if="scope.row.status === 'SUBMITED'" size="small">
              {{ loanStatusFormat(scope.row) }}
            </el-tag>
            <el-tag type="warning" v-else-if="scope.row.status === 'BACKING'" size="small">
              {{ loanStatusFormat(scope.row) }}
            </el-tag>
            <el-tag type="info" v-else size="small">{{ loanStatusFormat(scope.row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="settlePlanIndex" label="限制提前结清期数"></el-table-column>
        <el-table-column align="center" prop="cancelMemo" label="备注"></el-table-column>
        <el-table-column align="center" prop="followUpTeam" label="委案商/跟进团队"></el-table-column>
        <el-table-column align="center" label="查看详情">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleClick(scope.row)">详情</el-button>
            <template
              v-if="scope.row.status === 'SETTLED' && scope.row.capitalCode !== 'OWNBUSINESS' && scope.row.capitalCode !== 'FENGSHENGBUSINESSJQ' && scope.row.capitalCode !== 'YUANFENGBUSINESS' && scope.row.capitalCode !== 'FENGSHENGBUSINESSDR' && scope.row.capitalCode !== 'FENGSHENGBUSINESSZY'">
              <el-button type="text" size="small" @click="handleShow(scope.row, 'SettleReport', '结清报告')">结清报告
              </el-button>
            </template>
            <template v-if="scope.row.status === 'SETTLED' && scope.row.capitalCode === 'OWNBUSINESS' && zyItem">
              <el-button type="text" size="small" @click="handleShow(scope.row, 'GenerateSettleReport', '结清报告')">结清报告
              </el-button>
            </template>

            <!--偷懒写法-->
            <template
              v-if="scope.row.status === 'SETTLED' && scope.row.capitalCode === 'FENGSHENGBUSINESSJQ' && zyItem">
              <el-button type="text" size="small" @click="handleShow(scope.row, 'GenerateSettleReport', '结清报告')">结清报告
              </el-button>
            </template>
            <template
              v-if="scope.row.status === 'SETTLED' && scope.row.capitalCode === 'FENGSHENGBUSINESSDR' && zyItem">
              <el-button type="text" size="small" @click="handleShow(scope.row, 'GenerateSettleReport', '结清报告')">结清报告
              </el-button>
            </template>
            <template
              v-if="scope.row.status === 'SETTLED' && scope.row.capitalCode === 'FENGSHENGBUSINESSZY' && zyItem">
              <el-button type="text" size="small" @click="handleShow(scope.row, 'GenerateSettleReport', '结清报告')">结清报告
              </el-button>
            </template>
            <template v-if="scope.row.status === 'SETTLED' && scope.row.capitalCode === 'YUANFENGBUSINESS' && zyItem">
              <el-button type="text" size="small" @click="handleShow(scope.row, 'GenerateSettleReport', '结清报告')">结清报告
              </el-button>
            </template>


            <!-- 短信 -->
            <el-button type="text" size="small" @click="handleMessageSend(scope.row)">短信</el-button>

          </template>
        </el-table-column>
      </el-table>
    </div>


    <!--借款详情-->
    <template v-if="visible">
      <loan-detail @handleClose="visible = false" :title="title" :params="items" :dialogVisible="visible" />
    </template>

    <!--  那啥-->
    <template v-if="mcDialogVisible">
      <component @handleClose="mcDialogVisible = false" :is="ActiveCom" :title="mcTitle" :params="mcItems"
        :visible="mcDialogVisible" />
    </template>

    <!-- 短信发送 -->
    <template v-if="MessageDialogVisible">
      <BaseDialog width="45%" @onCancel="handleMsgCancel" :visible.sync="MessageDialogVisible" title="发短信">
        <el-form size="small" :model="MessageForm" :rules="MessageRules" ref="MessageForm" label-width="120px">
          <el-row>
            <el-col :span="18">


              <el-form-item label="短信模板：" prop="templateCode">
                <el-select style="width: 100%;" @change="handleSelectMsgTemplate" v-model="MessageForm.templateCode"
                  placeholder="请选择">
                  <el-option v-for="(item, index) in msgTemplateEnmu" :key="index" :label="item.templateName"
                    :value="item.templateCode">
                  </el-option>
                </el-select>
              </el-form-item>
              <template v-if="MessageForm.templateCode === 'COMPLAINT_RETURN_SMS'">
                <el-form-item label="投诉渠道：" prop="complaintChannel">
                  <el-input v-model="MessageForm.complaintChannel" @blur="handleInput" placeholder="请填写短信渠道" />
                </el-form-item>
              </template>
              <el-form-item label="短信内容：">
                <el-input type="textarea" v-model="MessageForm.context" placeholder="请输入发送号码" :rows="4" disabled />
              </el-form-item>
              <el-form-item label="发送号码：">
                <el-input placeholder="请输入发送号码" v-model="MessageForm.mobile" disabled />
              </el-form-item>
              <el-form-item>
                <el-button size="small" type="primary" @click="handleMessageSubmit">提 交</el-button>
              </el-form-item>

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

<script>
import LoanDetail from "./LoanDetail";
import SettleReport from "./SettleReport";
import GenerateSettleReport from './GenerateSettleReport.vue';
import * as moment from "moment";

export default {
  name: 'AddUserServiceDialog',
  components: {
    LoanDetail,
    SettleReport,
    GenerateSettleReport
  },
  props: {
    params: {
      type: Object,
      required: true
    },
  },
  data() {
    return {
      visible: false,
      activeComponents: "BaseInfo",
      title: "基本信息",
      items: {},
      mcDialogVisible: false,
      mcItems: null,
      mcTitle: "",
      ActiveCom: "",
      zyItem: "",
      data: [],

      // 短信模板
      msgTemplateEnmu: [],
      // 短信发送
      MessageForm: {
        templateCode: '',
        complaintChannel: '',
        loanNo: '',
        operator: '',
        context: '',
        mobile: ''
      },
      MessageRules: {
        templateCode: [{ required: true, message: "请选择短信模板", trigger: 'change' }],
        complaintChannel: [{ required: true, message: "请输入短信渠道", trigger: 'blur' }],
      },
      MessageDialogVisible: false,
    }
  },
  async created() {
    const btnUrl = localStorage.getItem('btnUrl');
    if (btnUrl) {
      this.zyItem = btnUrl
    } else {
      this.zyItem = null
    }
    const { clientNo, clientProductName } = this.params;
    const res = await this.$$post('/loan/getLoanListByClientNo/', { productName: clientProductName, clientNo: clientNo });
    const { success, result } = res.data;
    if (success && result !== null) {
      this.data = result;
    }
  },
  methods: {
    headerStyle() {
      return "tableHeaderStyle";
    },
    /*日期*/
    dateFormats: function (row, column) {
      let date = row[column.property]
      if (date === undefined) return '';
      return moment(date).format("YYYY-MM-DD")
    },
    //借款单状态
    loanStatusFormat: function (row) {
      let status = row['status'];
      return this.$enumUtils.toMsg('LoanStatuEnums', status);
    },
    capitalCodeFormat: function (row, column) {
      let capitalCodeStr = row['capitalCodeStr'];
      return this.$enumUtils.toMsg('CapitalEnums', capitalCodeStr);
    },
    // 切换选项卡
    handleClick(row) {
      console.log(row, '一行信息');
      this.visible = true;
      this.title = '借款详情';
      this.items = {
        ...this.params,
        ...row
      };
    },
    handleShow(row, com, title) {
      console.log(row, com, title, '当前行')
      this.mcDialogVisible = true;
      this.mcItems = {
        ...this.params,
        ...row
      };
      console.log(this.params, '什么鬼');
      console.log(this.mcItems, 'mmmcccc');
      this.mcTitle = title;
      this.ActiveCom = com;
    },
    // 获取短信模板
    async initMsgTemplate() {
      try {
        const { data, status } = await this.$$get('/detail/getSmsTemplate', {});
        if (status === 200 && data.success) {
          this.msgTemplateEnmu = data.result;
        }
      } catch (err) {
        console.log(err, '初始化短信模板异常')
      }
    },
    // 根据短信模板获取短信内容
    async initMsgContext() {
      try {
        const params = this.MessageForm
        const { data, status } = await this.$$post('/detail/getSmsTemplateContent', { ...params });
        if (status === 200 && data.success) {
          this.MessageForm.context = decodeURIComponent(data.result.smsContent);
          this.MessageForm.mobile = data.result.sendPhone;
        }
      } catch (err) {
        console.log(err, '初始化短信模板异常')
      }
    },

    // 短信发送弹框
    handleMessageSend(row) {
      const { loanNo, clientCell } = row;
      this.initMsgTemplate();
      this.MessageDialogVisible = true;
      this.MessageForm.loanNo = loanNo
      this.MessageForm.mobile = clientCell
      this.MessageForm.operator = localStorage.getItem('userName')
    },
    // 短信下拉
    async handleSelectMsgTemplate(val) {
      if (val !== 'COMPLAINT_RETURN_SMS') {
        this.initMsgContext()
      } else {
        this.MessageForm.context = '';
        this.MessageForm.mobile = '';
      }
    },
    // 暗示法
    handleInput(e) {
      const value = e.target.value;
      this.MessageForm.complaintChannel = value
      this.initMsgContext();
    },
    // 重置
    handleMsgCancel() {
      this.$refs['MessageForm'].resetFields();
    },
    // 发送短信提交
    handleMessageSubmit() {
      this.$refs['MessageForm'].validate(async (valid) => {
        if (!valid) {
          return false
        }

        try {
          const params = this.MessageForm
          const { data, status } = await this.$$post('/detail/sendSms', { ...params });
          if (status === 200 && data.success) {

            this.$message({
              message: '短信发送，操作成功',
              type: 'success'
            });

            this.MessageDialogVisible = false;
            this.handleMsgCancel();
            
          }
        } catch (err) {
          console.log(err, '短信发送失败')
        }
      })
    }

  }
}
</script>

<style></style>
