<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户姓名" prop="customer">
        <el-input
          v-model="queryParams.customer"
          placeholder="请输入客户姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="干系人" prop="stakeholder">
        <el-input
          v-model="queryParams.stakeholder"
          placeholder="请输入干系人姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="enable">
        <el-select v-model="queryParams.enable" placeholder="是否启用" clearable size="small" style="width: 240px">
          <el-option v-for="dict in enableOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <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="['system:personal:page:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:personal:page:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:personal:page:remove']"
        >删除</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="customer" width="280" />
      <el-table-column label="干系人姓名" align="center" prop="stakeholder" width="280" />
      <el-table-column label="启用" align="center" width="180">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enable" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remarks" /> -->
      <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-chat-line-square"
            @click="preview(scope.row)"
            v-hasPermi="['system:personal:message:query']"
          >预览</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:personal:page:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-chat-line-square"
            @click="handleMessage(scope.row)"
            v-hasPermi="['system:personal:message:list']"
          >留言</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" v-if="open" :visible.sync="open" width="1000px" append-to-body :close-on-click-modal=false>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="0" type="flex" justify="start">
          <el-col :span="8">
            
            <el-form-item label="客户姓名" prop="customerId">
              <el-select
                v-model="form.customer"
                filterable
                remote
                clearable
                placeholder="请输入名字/手机号查询"
                :remote-method="findCustomer"
                @change="customerChange"
                :loading="loadings">
                <el-option
                  v-for="item in customerOptions"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="干系人" prop="stakeholderId">
              <el-select
                v-model="form.stakeholder"
                filterable
                remote
                clearable
                placeholder="请输入名字/手机号查询"
                :remote-method="findStakeholder"
                @change="stakeholderChange"
                :loading="loadings">
                <el-option
                  v-for="item in stakeholderOptions"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>

            <!-- <el-form-item label="干系人姓名" prop="stakeholder">
              <el-input v-model="form.stakeholder" placeholder="请输入干系人姓名" />
            </el-form-item>  -->
          </el-col>
          <el-col :span="8">
            <el-form-item label="二维码" prop="qrcode">
              <el-image 
                style="width: 36px; height: 36px"
                :src="codeImg" 
                :preview-src-list="[codeUrl]">
              </el-image>
            </el-form-item>

            <el-form-item label="启用" prop="enable">
              <el-radio-group v-model="form.enable">
                <el-radio
                  v-for="dict in enableOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          </el-row>

        <el-form-item label="个人生平" prop="content">
          <editor v-model="form.content" :min-height="492" :params="editParams" ref="myEditor"/>
        </el-form-item>
      </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>
  </div>
</template>

<script>
import { listPersonal, getPersonal, delPersonal, addPersonal, updatePersonal, exportPersonal,changeEnable,getQrcode } from "@/api/system/personalPage";
import { listUser } from "@/api/system/appUser";
import Editor from '@/components/Editor';
import qrcodeImg from '@/assets/image/qrcode_img.jpg'

export default {
  name: "personalPage",
  components: {
    Editor,
  },
  data() {
    return {
      codeImg: qrcodeImg,
      codeUrl: "",
      // 遮罩层
      loading: true,
      loadings: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 个人页表格数据
      pageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否启用数据字典
      enableOptions: [],
      customerOptions:[],
      stakeholderOptions:[],
      // 查询参数
      customerParams: {
        enable: 0,
        searchValue: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customer: null,
        stakeholder: null,
        stakeholderBirthday: null,
        enable: null,
        modifyBy: null,
        modifyTime: null,
        remarks: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerId: [
          { required: true, message: "客户不能为空", trigger: "blur" },
        ],
        stakeholderId: [
          { required: true, message: "干系人不能为空", trigger: "blur" },
        ],
      },
      reFresh: 1,

      templateParam:{
        enable: 0
      },
      // 固定个人模板页
      templateRoute: "/template/t",
      templateList: [],
      editParams: {
        modName: '/personal/'
      }
    };
  },
  watch:{
    // 监听form值，只要有改变，则key值reFresh变更。
    // 然后自定义上传图片组件personalAvatar重新渲染
    form(){
      ++this.reFresh
    }
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then((response) => {
      this.enableOptions = response.data;
    });
  },
  methods: {
    findCustomer(query){
      if (query.length > 1) {
        this.loadings = true;
        this.customerParams.searchValue = query;
        listUser(this.customerParams).then(response => {
          this.loadings = false;
          this.customerOptions = response.data;
        });
      }
    },
    findStakeholder(query){
      if (query.length > 1) {
        this.loadings = true;
        this.customerParams.searchValue = query;
        listUser(this.customerParams).then(response => {
          this.loadings = false;
          this.stakeholderOptions = response.data;
        });
      }
    },
    customerChange(value){
      this.form.customerId = value;
      let obj = {};
      obj = this.customerOptions.find((item)=>{  
         return item.userId === value;
      });
      this.form.customer = obj.nickName
    },
    stakeholderChange(value){
      this.form.stakeholderId = value;
      let obj = {};
      obj = this.stakeholderOptions.find((item)=>{ 
         return item.userId === value;
      });
      this.form.stakeholder = obj.nickName
    },
    /** 查询个人页列表 */
    getList() {
      this.loading = true;
      listPersonal(this.queryParams).then(response => {
        this.pageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTemplateList(){
      listTemplate(this.templateParam).then(response => {
        this.templateList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        customer: null,
        avatar : null,
        stakeholder: null,
        stakeholderBirthday: null,
        enable: null,
        createBy: null,
        createTime: null,
        modifyBy: null,
        modifyTime: null,
        remarks: null,
        customerOptions: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.enable === "0" ? "启用" : "停用";
      this.$confirm(
        '确认要 ' + text + ' 吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return changeEnable(row.id, row.enable);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.enable = row.enable === "0" ? "1" : "0";
        });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加个人页";
      this.codeUrl = "";
    },
    /** 修改按钮操作 */
    handleUpdate(row) { 
      this.reset();
      const id = row.id || this.ids
      getPersonal(id).then(response => { 
        this.form = response.data;
        this.getQrcodeImg(row);
        this.open = true;
        this.title = "修改个人页";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePersonal(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addPersonal(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除个人页编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPersonal(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有个人页数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportPersonal(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    getQrcodeImg(row) {
      const pid = row.id;
      const tid = row.templateId;
      // const route = this.templateList.find(item => item.id === tid).route;
      const url = window.location.origin + this.templateRoute+'/' + pid
      const param = {url:url}
      getQrcode(param).then(res => {
        this.codeUrl = "data:image/gif;base64," + res.img;
      });
    },
    viewPage(){
      debugger
      const pid = this.form.id;
      const tid = this.form.templateId;
      // const route = this.templateList.find(item => item.id === tid).route;
      console.log(window.location.origin + this.templateRoute+'/' + pid)
      var win = window.open(window.location.origin + this.templateRoute+'/' + pid);
      win.document.title='个人页 - '+this.form.stakeholder
    },
    preview(row) {
      const pid = row.id;
      const tid = row.templateId;
      // const route = this.templateList.find(item => item.id === tid).route;
      var win = window.open(window.location.origin + this.templateRoute+'/' + pid);
    },
    handleMessage(row) {
      this.$router.push({
        path: "/personal/message",
        query: {
          mid: row.id
        }
      });
    },
    img(row) {
      this.$router.push({
        path: "/personal/pic",
        query: {
          pid: row.id
        }
      });
    },
    video(row) {
      this.$router.push({
        path: "/personal/video",
        query: {
          pid: row.id
        }
      });
    },
  }
};
</script>

<style>
/* .el-dialog__body {
  padding: 10px 20px;
} */
/* .el-form-item {
  margin-bottom: 8px;
} */
</style>