<!--
 * @Description: 
 * @Author: gcz
 * @Date: 2023-09-18 10:24:00
 * @LastEditors: gcz
 * @LastEditTime: 2023-09-25 17:16:43
 * @FilePath: \gybank_webui\src\views\tool\customerform\fdform\list.vue
 * @Copyright: Copyright (c) 2016~2023 by gcz, All Rights Reserved. 
-->
<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">

        <el-form-item v-for="(item) in queryList" :key="item.columnName" :label="item.columnComment" >
          <el-input
            v-if="item.compType=='input'||item.compType=='inputNumber'||item.compType=='textarea'||item.compType=='slider'||item.compType=='barCode'||item.compType=='editor'"
            v-model="queryParams.queryList[item.columnName]"
            :placeholder="item.columnComment"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
          <el-select v-if="item.compType=='select'||item.compType=='radio'"  clearable v-model="queryParams.queryList[item.columnName]" :placeholder="item.columnComment">
            <el-option v-for="option in item.options" :key="option.columnName" :value="option.value" :label="option.label"></el-option>
          </el-select>
          <el-select v-if="item.compType=='checkbox'" clearable v-model="queryParams.queryList[item.columnName]" multiple :placeholder="item.columnComment">
            <el-option v-for="option in item.options" :key="option.columnName" :value="option.value" :label="option.label"></el-option>
          </el-select>
          <el-select v-if="item.compType=='Switch'" clearable v-model="queryParams.queryList[item.columnName]" :placeholder="item.columnComment">
            <!-- <el-option v-for="option in item.options" :key="option.columnName" :value="option.value">{{option.label}}</el-option> -->
            <el-option value="1" label="是"></el-option>
            <el-option value="0" label="否"></el-option>
          </el-select>
          <el-cascader
            v-if="item.compType=='cascader'"
            :props="{ checkStrictly: true }"
            v-model="queryParams.queryList[item.columnName]"
            :options="item.options">
          </el-cascader>
          <el-color-picker v-if="item.compType=='colorPicker'" v-model="queryParams.queryList[item.columnName]"></el-color-picker>
          <el-rate v-if="item.compType=='rate'" v-model="queryParams.queryList[item.columnName]"></el-rate>
          <el-time-picker
            v-if="item.compType=='time'"
            value-format="HH:mm:ss"
            v-model="queryParams.queryList[item.columnName]"
            :placeholder="item.columnComment">
          </el-time-picker>
          <el-date-picker
            v-if="item.compType=='date'"
            v-model="queryParams.queryList[item.columnName]"
            align="right"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="item.columnComment">
          </el-date-picker>

        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" 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"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:role:add']"
          >新增</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:role:edit']"
          >修改</el-button>
        </el-col> -->
        <!-- <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:role:remove']"
          >删除</el-button>
        </el-col> -->
        <!-- <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:role:export']"
          >导出</el-button>
        </el-col> -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="dataList" header-align="center" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->

        <!-- <el-table-column v-for="column in columns" :label="column.label" :prop="column.prop"></el-table-column> -->

        <el-table-column v-for="column in filterColumns" :key="column.columnName" :label="column.label" align="center">
        <template slot-scope="scope">
          <!-- 根据不同的组件类型进行渲染 -->
          <template v-if="column.compType === 'select'">
            <span>{{ getOptionLabel(column.columnName, scope.row[column.columnName]) }}</span>
          </template>
          <template v-else-if="column.compType === 'radio' || column.compType === 'checkbox'">
            <span>{{ getOptionLabel(column.columnName, scope.row[column.columnName]) }}</span>
          </template>
          <template v-else-if="column.compType === 'upload'">
            <!-- <span>{{ getOptionLabel(column.columnName, scope.row[column.columnName]) }}</span> -->
            <a :href="uploadItem.url" v-for="(uploadItem,i) in getOptionLabel(column.columnName, scope.row[column.columnName])" :key="i" style="color: blue;"> {{ uploadItem.name }}</a>
          </template>
          <template v-else>
            <!-- {{ column.columnName }} -->
            <span>{{ scope.row[column.columnName] }}</span>
          </template>
        </template>
      </el-table-column>
  
        <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" fixed="right" width="180" class-name="small-padding fixed-width">
          <template slot-scope="scope" v-if="scope.row.roleId !== 1">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:role:edit']"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:role:remove']"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleView(scope.row)"
              v-hasPermi="['system:role:remove']"
            >预览</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"
      />
    </div>
  </template>
  
  <script>
  import { getTableInfo,frmPageList ,frmDelete} from "@/api/customerform/customerformapi";
  import { treeselect as menuTreeselect, roleMenuTreeselect } from "@/api/system/menu";
  
  export default {
    name: "tempalteList",
    dicts: ['sys_normal_disable'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 角色表格数据
        dataList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          propertyList:[],
          queryList:{},
          formName: undefined
        },
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 表单校验
        rules: {
          roleName: [
            { required: true, message: "角色名称不能为空", trigger: ["change","blur"] }
          ],
          roleKey: [
            { required: true, message: "权限字符不能为空", trigger: ["change","blur"] }
          ],
          roleSort: [
            { required: true, message: "角色顺序不能为空", trigger: ["change","blur"] }
          ]
        },
        // 本页新增开始
        tableName:'',
        tableInfo:{},
        columns:[],
        filterColumns:[],
        queryList:[],

      };
    },
    created() {
        this.tableName = this.$route.query?.tableName;
        this.getTableInfo();
    //    this.getList();
    },
    methods: {
      getTableInfo(){
        getTableInfo({tableName:this.tableName}).then(res=>{
            this.tableInfo = res.data;
            // console.log('this.tableInfo',this.tableInfo);
            this.queryParams.propertyList = res.data.propertyList;
            this.queryList = res.data.queryList;
            // console.log('this.queryList',this.queryList);
            this.setQueryParams( this.queryList);
            for (const item of  res.data.propertyList) {
                const column = {
                    label: item.columnComment,
                    columnName: item.columnName,
                    compType:item.compType,
                    options:item.options
                };
                this.columns.push(column);
            }
            // console.log(' this.columns', this.columns);
            this.getList();
            // console.log('getTableInfo',res);
        }).finally(()=>{
            this.loading = false;
        })
      },
      setQueryParams(params){
        for (let i=0; i<params.length;i++){
          // console.log('this.queryList[i]',this.queryList[i]);
          if(this.queryList[i].compType=='rate'){
            this.$set(this.queryParams.queryList,this.queryList[i].columnName,null)
          }else{
            this.$set(this.queryParams.queryList,this.queryList[i].columnName,'')
          }
          
        }
        // console.log('this.queryParams',this.queryParams);
      },
      /** 查询角色列表 */
      getList() {
        this.loading = true;
        this.queryParams.tableName = this.tableName;
        frmPageList(this.queryParams).then(response => {
            this.dataList = response.data.rows;
            // console.log('this.columns',this.columns);
            this.total = response.data.total;
            this.filterColumns = this.columns.filter(item => {
                // console.log('item',item);
                // console.log('0000000000',this.dataList[0]);
                return  this.dataList[0]?.hasOwnProperty(item.columnName);
            });
            console.log(' this.filterColumns', this.filterColumns);
            this.loading = false;
          }
        );
      },
      getOptionLabel(columnName, value) {
        // console.log('columnName',columnName);
        // console.log('value',value);
      // 根据columnName在columns找到对应的column，然后根据value在options找到对应的label
      const column = this.columns.find(c => c.columnName === columnName);
      if(column.compType=='upload' && value){
        // console.log('value', JSON.parse(value) );
        // console.log('column',column);
        return JSON.parse(value)
      }
      // console.log('column',column);
      if (column && column.options) {
        const option = column.options.find(option => option.value == value);
        return option ? option.label : '';
      }
      return '';
    },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 取消按钮（数据权限）
      cancelDataScope() {
        this.openDataScope = false;
        this.reset();
      },
      // 表单重置
      reset() {
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.menuExpand = false,
        this.menuNodeAll = false,
        this.deptExpand = true,
        this.deptNodeAll = false,
        this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.setQueryParams( this.queryList);
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handleDataScope":
            this.handleDataScope(row);
            break;
          case "handleAuthUser":
            this.handleAuthUser(row);
            break;
          default:
            break;
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.$router.push("/vform/edit?formID=" + "&type=add" + "&templateId=" + this.tableInfo.templateId + "&formCode=" + this.tableInfo.tableName);
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        // console.log('row',row);
        const formID = row.id;
        // console.log('formID',formID);
        this.$router.push("/vform/edit?formID=" + formID + "&type=edit" + "&templateId=" + row.template_id + "&formCode=" + row.form_code);
      },
      /** 预览 */
      handleView(row){
        const formID = row.id;
        this.$router.push("/vform/edit?formID=" + formID + "&type=view" + "&templateId=" + row.template_id + "&formCode=" + row.form_code);
      },
      /** 选择角色权限范围触发 */
      dataScopeSelectChange(value) {
        if(value !== '2') {
          this.$refs.dept.setCheckedKeys([]);
        }
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.roleId != undefined) {
              this.form.menuIds = this.getMenuAllCheckedKeys();
              updateRole(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.menuIds = this.getMenuAllCheckedKeys();
              addRole(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        // const roleIds = row.id || this.ids;
        const id = row.id;
        this.$modal.confirm('是否确认删除角色编号为"' + id + '"的数据项？').then(()=> {
          return frmDelete({id:id,tableName:this.tableName});
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch((err) => {
          console.log('err',err);
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/role/export', {
          ...this.queryParams
        }, `role_${new Date().getTime()}.xlsx`)
      },
    }
  };
  </script>
  