<template>
  <div class="app-container">
    <el-card class="fiche">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"
        >收起</right-toolbar
      >
      <span
        style="
          margin-bottom: 10px;
          color: #333333;
          font: 14px Helvetica Neue, Helvetica, PingFang SC, Tahoma, Arial,
            sans-serif;
        "
        >所选条件:</span
      >
      <div style="float: right; margin-right: 1%">
        <el-button
          type="cyan"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          style="float: "
          >重置</el-button
        >
      </div>
      <hr style="margin-top: 16px" />
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="100px"
      >
        <el-form-item label="资金方名称" prop="scyName">
          <el-input
            v-model="queryParams.scyName"
            placeholder="请输入资金方名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            maxlength="15"
          />
        </el-form-item>
        <el-form-item label="资金方类型" align="center" prop="smiType">
          <el-select v-model="queryParams.smiType">
            <el-option
              v-for="(item, index) in formulaOptions"
              :key="index"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户经理" prop="smiManager">
          <el-input
            v-model="queryParams.smiManager"
            placeholder="请输入客户经理"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            maxlength="15"
          />
        </el-form-item>
        <el-form-item label="联系人姓名" prop="smiContract">
          <el-input
            v-model="queryParams.smiContract"
            placeholder="请输入联系人姓名"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            maxlength="15"
          />
        </el-form-item>
        <el-form-item label="联系人电话" prop="smiContractPhone">
          <el-input
            v-model="queryParams.smiContractPhone"
            placeholder="请输入联系人电话"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
            maxlength="15"
          />
        </el-form-item>
      </el-form>
    </el-card>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fundSide:fundSide:add']"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="fundList"
      @selection-change="handleSelectionChange"
      stripe
      border
    >
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column label="资金方编号" align="center" prop="scyId" />
      <el-table-column label="资金方名称" align="center" prop="scyName" />
      <el-table-column
        label="资金方类型"
        :formatter="formulaFormat"
        align="center"
        prop="smiType"
      />
      <el-table-column
        label="社会统一信用代码"
        align="center"
        prop="scySocialCode"
      />
      <el-table-column label="联系人名称" align="center" prop="smiContract" />
      <el-table-column
        label="联系人电话"
        align="center"
        prop="smiContractPhone"
      />
      <el-table-column label="客户经理" align="center" prop="smiManager" />
      <!-- <el-table-column
        label="资金方状态"
        :formatter="formulaFormatSend"
        align="center"
        prop="scyStatus"
      /> -->
      <el-table-column label="资金方状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.scyStatus"
            active-value="00"
            inactive-value="01"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fundSide:fundSide:update']"
            v-if="scope.row.scyStatus=='01'"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资金方对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        :inline="true"
        :disabled="disableds"
      >
        <el-divider content-position="left">渠道信息</el-divider>
        <el-form-item label="资金方名称" prop="scyName">
          <el-input
            v-model="form.scyName"
            style="width: 215px"
            placeholder="请输入资金方名称"
            maxlength="15"
          />
        </el-form-item>
        <el-form-item prop="smiType" label="资金方类型">
          <el-select v-model="form.smiType">
            <el-option
              v-for="(item, index) in formulaOptions"
              :key="index"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="合作协议签署"
          align="center"
          prop="smiAgreementType"
        >
          <el-select v-model="form.smiAgreementType">
            <el-option
              v-for="(item, index) in formulaOptionsSend"
              :key="index"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资金方网点" prop="smiAddress">
          <el-input
            v-model="form.smiAddress"
            style="width: 215px"
            placeholder="请输入资金方网点"
            maxlength="15"
          />
        </el-form-item>
        <el-form-item label="社会统一信用代码" prop="scySocialCode">
          <el-input
            v-model="form.scySocialCode"
            style="width: 215px"
            placeholder="请输入社会统一信用代码"
            maxlength="18"
          />
        </el-form-item>
        <el-form-item label="客户经理" prop="smiManager">
          <el-input
            v-model="form.smiManager"
            style="width: 215px"
            placeholder="请输入客户经理"
            maxlength="15"
          />
        </el-form-item>
        <el-form-item label="联系人姓名" prop="smiContract">
          <el-input
            v-model="form.smiContract"
            style="width: 215px"
            placeholder="请输入联系人姓名"
            maxlength="15"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="联系人电话" prop="smiContractPhone">
          <el-input
            v-model="form.smiContractPhone"
            style="width: 215px"
            placeholder="请输入联系人电话"
            maxlength="11"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="补充描述">
          <el-input
            v-model="form.smiDesc"
            type="textarea"
            placeholder="请输入内容"
            maxlength="100"
            style="width: 558px"
          ></el-input>
        </el-form-item>
        <el-form-item label="合作协议">
          <el-upload
            ref="upload"
            class="upload-demo"
            :class="{ uoloadSty: showBtnImg, disUoloadSty: noneBtnImg }"
            action=""
            accept=".jpg, .jpeg, .png, .JPG, .JPEG, .PNG"
            :http-request="sfzRequest"
            :on-preview="handlePictureCardPreview"
            :on-remove="beforeRemove"
            :on-change="dealImgChange"
            multiple
            :limit="20"
            :on-exceed="handleExceed"
            list-type="picture-card"
            :file-list="sfzList"
            :auto-upload="true"
          >
            <el-button slot="trigger" size="small" type="primary"
              >点击选择</el-button
            >
          </el-upload>
        </el-form-item>
        <!-- <el-button
          style="margin-left: 10px"
          size="small"
          type="success"
          @click="submitUpload"
          >上传到服务器</el-button
        > -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="sfzVisible">
      <img width="100%" :src="sfzImageUrl" alt="" />
    </el-dialog>
  </div>
</template>


<script>
import {
  listFund,
  getFund,
  addFund,
  updateFund,
  fundSideStatus,
} from "@/api/fundSide/fundSide";
import Editor from "@/components/Editor";
import { uploadFileNew } from "@/api/common/file";
import { getToken } from "@/utils/auth";

export default {
  name: "fundSide",
  components: {
    Editor,
  },
  data() {
    return {
      //图片预览
      sfzImageUrl: "",
      sfzVisible: false,
      showBtnImg: false,
      noneBtnImg: false,
      limitCountImg: 1,
      // id隐藏
      isShow: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //联系人隐藏
      disabled: false,
      disableds: false,
      // 总条数
      total: 0,
      // 资金方表格数据
      fundList: [],
      //姓名
      nameList: [],
      //字典
      formulaOptions: [],
      formulaOptionsSend: [],
      UserList: [],
      enclosureList: [],
      sfzList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scyName: null,
        smiType: null,
        smiManager: null,
        smiContract: null,
        smiContractPhone: null,
        sfsContent: null,
        sfsIsDel: null,
        sfsRemark: null,
        ssId: null,
        ssName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        scyName: [
          {
            required: true,
            message: "资金方名称不能为空",
            trigger: ["change", "blur"],
          },
          {
            pattern: /^[\u2E80-\u9FFF]|\w|[,，\.。]+$/,
            message: "资金方名称不能含有特殊字符",
            trigger: "blur",
          },
        ],
        smiAddress: [
          {
            required: true,
            message: "资金方网点不能为空",
            trigger: ["change", "blur"],
          },
                  {
            pattern: /^[\u2E80-\u9FFF]|\w|[,，\.。]+$/,
            message: "资金方网点不能含有特殊字符",
            trigger: "blur",
          },
        ],
        smiType: [
          {
            required: true,
            message: "资金方类型不能为空",
            trigger: ["change", "blur"],
          },
        ],
        smiAgreementType: [
          {
            required: true,
            message: "合作协议签署不能为空",
            trigger: ["change", "blur"],
          },
        ],
        scySocialCode: [
          {
            required: true,
            message: "社会统一信用代码不能为空",
            trigger: ["change", "blur"],
          },
        ],
        smiManager: [
          {
            required: true,
            message: "客户经理不能为空",
            trigger: ["change", "blur"],
          },
          {
            pattern: /^[\u2E80-\u9FFF]|\w|[,，\.。]+$/,
            message: "客户经理不能含有特殊字符",
            trigger: "blur",
          },
        ],
        smiContract: [
          {
            required: true,
            message: "联系人姓名不能为空",
            trigger: ["change", "blur"],
          },
          {
            pattern: /^[\u2E80-\u9FFF]|\w|[,，\.。]+$/,
            message: "联系人姓名不能含有特殊字符",
            trigger: "blur",
          },
        ],
        smiContractPhone: [
          {
            required: true,
            message: "联系人电话不能为空",
            trigger: ["change", "blur"],
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_smi_type").then((response) => {
      this.formulaOptions = response.data;
    });
    this.getDicts("sys_agreement_type").then((response) => {
      this.formulaOptionsSend = response.data;
    });
  },
  methods: {
    /** 查询资金方列表 */
    getList() {
      this.loading = true;
      listFund(this.queryParams).then((response) => {
        this.fundList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        scyId: null,
        scyName: null,
        smiType: null,
        smiManager: null,
        smiContract: null,
        smiContractPhone: null,
        sfsContent: null,
        sfsIsDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        sfsRemark: null,
        ssId: null,
        ssName: null,
      };
      this.noneBtnImg = false;
      this.enclosureList = [];
      this.sfzList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.scyId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    //资方类型
    formulaFormat(row, column) {
      return this.selectDictLabel(this.formulaOptions, row.smiType);
    },
    //奖项
    formulaFormatSend(row, column) {
      return this.selectDictLabel(
        this.formulaOptionsSend,
        row.smiAgreementType
      );
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.disableds = false;
      this.disabled = false;
      this.title = "添加资金方";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const scyId = row.scyId || this.ids;
      getFund(scyId).then((response) => {
        console.log(response);
        this.form = response.data.list[0];
        if (response.data.data && response.data.data.length != 0) {
          this.sfzList.push({
            uid: response.data.data[0].uid,
            url: response.data.data[0].pfiUrl + "/" + getToken(),
          });
          
          this.noneBtnImg = true;
        }
        this.open = true;
        this.disableds = false;
        this.disabled = true;
        this.title = "修改资金方";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.reset();
      const scyId = row.scyId || this.ids;
      getFund(scyId).then((response) => {
        console.log(response);
        this.form = response.data.list[0];
        if (response.data.data && response.data.data.length != 0) {
          this.sfzList.push({
            name: "合作协议",
            url: response.data.data[0].pfiUrl + "/" + getToken(),
          });
          this.noneBtnImg = true;
        }
        this.open = true;
        this.disableds = true;
        this.title = "资金方详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        this.form.smiAgreement = this.sfzList;
        console.log(this.sfzList)
        console.log(this.form.smiAgreement);
        if (valid) {
          if (this.form.scyId != null) {
            const loading = this.$loading({
              lock: true,
              text: "Loading",
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)",
            });
            updateFund(this.form)
              .then((response) => {
                loading.close();
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .catch((response) => {
                loading.close();
              });
          } else {
            const loading = this.$loading({
              lock: true,
              text: "Loading",
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)",
            });
            addFund(this.form)
              .then((response) => {
                loading.close();
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .catch((response) => {
                loading.close();
              });
          }
        }
      });
    },
    //状态变更
    handleStatusChange(row) {
      let text = row.scyStatus === "00" ? "启用" : "停用";
      this.$confirm("确认要" + text + '"' + row.scyName + '"吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return fundSideStatus(row.scyId, row.scyStatus);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.scyStatus = row.scyStatus === "00" ? "01" : "00";
        });
    },
    //文件移除提示
    beforeRemove(file, sfzList) {
      for (let i = 0; i < this.sfzList.length; i++) {
        if (file.uid == this.sfzList[i].uid) {
          this.sfzList.splice(i, 1);
          break;
        }
      }
      this.noneBtnImg = sfzList.length >= this.limitCountImg;
    },
    handleExceed(file, sfzList) {
      this.$message.warning(`当前限制选择 20 个文件`);
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.sfzImageUrl = file.url;
      this.sfzVisible = true;
    },
    dealImgChange(file, sfzList) {
      this.noneBtnImg = sfzList.length >= this.limitCountImg;
    },
    //上传
    submitUpload() {
      this.$refs.upload.submit();
    },
    //手动上传文件触发
    sfzRequest(param) {
      let fileObj = param.file; // 相当于input里取得的files
        const isLt2M = fileObj.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        loading.close();
      }
      const isJPG = fileObj.type === "image/jpeg"||
      fileObj.type === "image/png";
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG ,PNG格式!");
         loading.close();
      }
      let fd = new FormData(); // FormData 对象
      fd.append("file", fileObj); // 文件对象
      fd.append("fileType", "00"); //文件类型
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      uploadFileNew(fd).then((response) => {
        if (response) {
          this.sfzList.push({
            uid: response.fileId,
            url: response.url + "/" + getToken(),
          });
          setTimeout(() => {
            loading.close();
          }, 2000);
        }
      }).catch((response) => {
              loading.close();
            });
    },
  },
};
</script>
