<template>
  <div class="obpm-common-tool">
    <div class="obpm-title">
      <div class="d-inline-block">
        <i class="el-icon-folder title-icon"></i>
        <div class="title-name d-inline-block ml-2">widget</div>
      </div>
      <div class="bar d-inline-block float-right">
        <el-button type="primary" size="small" @click="createRoles">{{$t('btns.new')}}</el-button>
        <el-button type="danger" plain size="small" @click="showDeleteConfirm">{{$t('btns.delete')}}</el-button>
      </div>
    </div>
    <!-- widgetList中的publicTable -->
    <publicTable ref="publictable" 
      @onRowClick='onRowClick' 
      @handleSelectionChange='handleSelectionChange'
      @handleSizeChange='handleSizeChange'
      @handleCurrentChange='handleCurrentChange'
      @updataParams='updataParams'
      @getData='getWidgets'
    ></publicTable>
    <el-dialog title="Widget" :visible.sync="dialogFormVisible" width="50%" top="30px" @close="resetWidgetForm('widgetForm')">
      <div class="dialog-content">
        <el-form :model="widgetForm" :rules="rules" ref="widgetForm" size="small" label-position="left">
          <el-form-item :label="$t('widget.name')" label-width="120px" prop="name">
            <el-input v-model="widgetForm.name" autocomplete="off" class="controlWidth"></el-input>
          </el-form-item>
          <el-form-item :label="$t('widget.type')" label-width="120px" prop="type">
            <el-select v-model="widgetForm.type" :placeholder="$t('placeholder.select')" @change="typeChange">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="统计类型" label-width="120px" v-if="widgetForm.type == 'checkin'">
            <el-radio-group v-model="widgetForm.countType">
              <el-radio label="none">无</el-radio>
              <el-radio label="month">月份</el-radio>
              <el-radio label="quarter">季度</el-radio>
              <el-radio label="year">年份</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="$t('widget.summary')" label-width="120px" v-if="isTypeOptions.isActionSummary" prop="actionSummary">
            <el-row>
              <el-col :span="10">
                <el-select v-model="widgetForm.actionSummary" :placeholder="$t('placeholder.select')">
                  <el-option
                    v-for="item in actionViewOptions"
                    :key="item.id"
                    :label="item.showName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
          <!-- <el-form-item label="摘要:" label-width="120px" v-show="isTypeOptions.isActionSummary">
            <el-input v-model="widgetForm.actionSummary" autocomplete="off" class="controlWidth"></el-input>
          </el-form-item> -->
          <el-form-item :label="$t('widget.module')" label-width="120px" v-show="isTypeOptions.isModule">
            <el-select v-model="widgetForm.moduleid" :placeholder="$t('placeholder.select')" @change="moduleChange">
              <el-option
                v-for="item in moduleOptions"
                :key="item.id"
                :label="item.value"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('widget.onactionview')" label-width="120px" v-if="isTypeOptions.isActionView">
            <el-row>
              <el-col :span="10">
                <el-select v-model="widgetForm.actionView" :placeholder="$t('placeholder.select')">
                  <el-option
                    v-for="item in actionViewOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-checkbox v-model="widgetForm.iconShow">{{$t('radio.widely_use')}}</el-checkbox>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item :label="$t('widget.onactionreport')" label-width="120px" v-if="isTypeOptions.isCustomizeReport" prop="customizeReport">
            <el-row>
              <el-col :span="10">
                <el-select v-model="widgetForm.customizeReport" :placeholder="$t('placeholder.select')">
                  <el-option
                    v-for="item in actionViewOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-checkbox v-model="widgetForm.iconShow">{{$t('radio.widely_use')}}</el-checkbox>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item :label="$t('widget.chart')" label-width="120px" v-show="isTypeOptions.isChart">
            <el-row>
              <el-col :span="10">
                <el-select v-model="widgetForm.chart" :placeholder="$t('placeholder.select')">
                  <el-option
                    v-for="item in actionViewOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-checkbox v-model="widgetForm.iconShow">{{$t('radio.widely_use')}}</el-checkbox>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item :label="$t('widget.url')" label-width="120px" v-if="isTypeOptions.isActionUrl" prop="actionUrl">
            <el-row>
              <el-col :span="10">
                <el-input type="textarea" :rows="2" v-model="widgetForm.actionUrl" class="controlWidth"></el-input>
              </el-col>
              <el-col :span="8">
                <el-checkbox v-model="widgetForm.iconShow">{{$t('radio.widely_use')}}</el-checkbox>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item :label="$t('widget.iscript')" label-width="120px" v-if="isTypeOptions.isIsript" prop="iscript">
            <el-row>
              <el-col :span="14">
                <el-input type="textarea" :rows="2" v-model="widgetForm.iscript" class="controlWidth"></el-input>
                <i class="el-icon-edit-outline" @click="showScriptEditor('iscript')"></i>

              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item :label="$t('widget.order_number')" label-width="120px" prop="orderno">
            <!-- <el-input v-model="widgetForm.orderno" autocomplete="off" class="controlWidth"></el-input> -->
            <el-input-number v-model="widgetForm.orderno" :min="0" :max="10000000" size="small" class="controlWidth"></el-input-number>
          </el-form-item>
          <el-form-item :label="$t('widget.auth_mode')" label-width="120px">
            <el-radio v-model="widgetForm.authMode" label="0">{{$t('widget.all_roles')}}</el-radio>
            <el-radio v-model="widgetForm.authMode" label="1">{{$t('widget.same_roles')}}</el-radio>
            <el-radio v-model="widgetForm.authMode" label="2">{{$t('widget.selected_users')}}</el-radio>
          </el-form-item>
          <el-form-item v-if="widgetForm.authMode=='1'" label-width="120px">
            <el-input v-model="widgetForm.authRolesName" class="controlWidth"></el-input>
            <!-- 需要传值给弹窗进行数据回选 -->
            <el-button type="primary" plain @click="chooseRole" class="ml-2">{{$t('btns.select')}}</el-button>
            <el-button type="danger" plain @click="onRoleClean_detail">{{$t('btns.clean')}}</el-button>
          </el-form-item>
          <el-form-item v-if="widgetForm.authMode=='2'" label="Iscript脚本内容">
            <el-col :span="14">
              <el-input type="textarea" :rows="2" v-model="widgetForm.userScript" class="controlWidth" placeholder="脚本返回用户对象集合"></el-input>
              <i class="el-icon-edit-outline" @click="showScriptEditor('userScript')"></i>
            </el-col>
          </el-form-item>
          <el-form-item :label="$t('widget.support_type')" label-width="120px">
            <el-radio v-model="widgetForm.widgetType" label="0">{{$t('widget.general_widget')}}</el-radio>
            <el-radio v-model="widgetForm.widgetType" label="1">{{$t('widget.webpage_widget')}}</el-radio>
            <el-radio v-model="widgetForm.widgetType" label="2">{{$t('widget.mobile_widget')}}</el-radio>
          </el-form-item>
          <el-form-item :label="$t('widget.publish_or_not')" label-width="120px">
            <el-radio v-model="widgetForm.published" label="true">{{$t('widget.yes')}}</el-radio>
            <el-radio v-model="widgetForm.published" label="false">{{$t('widget.no')}}</el-radio>
          </el-form-item>
          <el-form-item :label="$t('widget.height')" label-width="120px" v-if="showHeightLabel">
            <el-input v-model="widgetForm.height" class="controlWidth"></el-input>px
          </el-form-item>
          <el-form-item :label="$t('widget.frequency')" label-width="120px" v-if="showCarousel">
            <el-input v-model.number="widgetForm.frequency" class="controlWidth"></el-input>{{$t('widget.second')}}/{{$t('widget.time')}}
          </el-form-item>
          <el-form-item :label="$t('widget.pic')" label-width="120px" v-if="showCarousel">
            <!-- <el-input v-model="widgetForm.carouselImg" class="controlWidth"></el-input>px -->
            <img class="imgIcon" :src="getLogoUrl(widgetForm.carouselImg)" v-show="widgetForm.carouselImg" />
            <fileUpload 
            :visible.sync="fileUploadVisible" 
            v-if="fileUploadVisible" 
            @checkUpload="onCheckUpload" 
          />
            <el-button class="obpm-btn-default mr-1" plain @click="fileUploadVisible=true" type="primary">{{$t('btns.choose')}}</el-button>
            <el-button class="obpm-btn-default mr-1" plain @click="widgetForm.carouselImg=''">{{$t('btns.clean')}}</el-button>
          </el-form-item>
          <el-form-item :label="$t('widget.icon_type')" label-width="120px">
            <el-radio v-model="icon.icontype" label="img">{{$t('widget.pic')}}</el-radio>
            <el-radio v-model="icon.icontype" label="font">{{$t('widget.font_icon')}}</el-radio>
          </el-form-item>
          <el-form-item :label="$t('widget.icon')" label-width="120px">
            <div v-if="icon.icontype == 'img'">
              <img class="imgIcon" :src="getLogoUrl(icon.imgUrl)" />
              <el-button style="vertical-align: bottom;" class="obpm-btn-default mr-1" plain @click="selectImg" type="primary">{{$t('btns.choose')}}</el-button>
            </div>
            <div v-if="icon.icontype == 'font'">
              <i :class="icon.fontUrl" :style="fontStyle"></i>
              <el-button class="obpm-btn-default mr-1" plain @click="selectFont" type="primary">{{$t('btns.choose')}}</el-button>
              <ColorPicker ref="fontcolor" style="vertical-align: bottom;"  @setColor="setColor"  v-model="icon.iconFontColor" :colorValue="icon.iconFontColor" valueLabel="iconFontColor"></ColorPicker>
            </div>
          </el-form-item>
          <el-form-item :label="$t('widget.title_color')" label-width="120px">
            <ColorPicker style="vertical-align: bottom;"  @setColor="setColor" v-model="widgetForm.titleColor" :colorValue="widgetForm.titleColor" valueLabel="titleColor"></ColorPicker>
            <span style="color:green">{{$t('view.temp_support_pc')}}</span>
          </el-form-item>
          <el-form-item :label="$t('widget.title_bg_color')" label-width="120px">
            <ColorPicker style="vertical-align: bottom;"  @setColor="setColor" v-model="widgetForm.titleBColor" :colorValue="widgetForm.titleBColor" valueLabel="titleBColor"></ColorPicker>
            <span style="color:green">{{$t('view.temp_support_pc')}}</span>
          </el-form-item>
          <el-form-item :label="$t('widget.title_bar_color')" label-width="120px">
            <ColorPicker style="vertical-align: bottom;"  @setColor="setColor" v-model="widgetForm.titleBarColor" :colorValue="widgetForm.titleBarColor" valueLabel="titleBarColor"></ColorPicker>
            <span style="color:green">{{$t('view.temp_support_pc')}}</span>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exitEditDetail" size="small">{{$t('btns.cancel')}}</el-button>
        <el-button type="primary" @click="save('widgetForm')" size="small" :loading="btnLoading">{{$t('btns.confirm')}}</el-button>
      </div>
    </el-dialog>
    <icon_select
      :visible.sync="iconSelectCheck"
      :logoUrl="icon.imgUrl"
      @select-ok="onSelectIconOk"
      v-if="iconSelectCheck"
    />
    <font_select
      :visible.sync="fontSelectCheck"
      :logoUrl="icon.fontUrl"
      @select-ok="onSelectFontOk"
      v-if="fontSelectCheck"
    />
    <!-- 脚本选择器弹窗 -->
    <!-- scriptEditorVisible:弹窗显示   showScritptEditorCode：将文本框的值传给编译器  handleScriptEditor：将编译器的值传给textarea-->
    <ScriptEditorSelect
      v-if="scriptEditorVisible"
      :scriptEditorVisible="scriptEditorVisible"
      :editorCode="showScritptEditorCode"
      @closeScriptEditorDialog="scriptEditorVisible = false"
      @saveScriptEditor="handleScriptEditor"
    />
    <el-dialog :title="$t('widget.choose_role')" v-if="roleVisible" :visible.sync="roleVisible">
      <div class="obpm-title">
        <div class="d-inline-block">
          <i class="el-icon-folder title-icon"></i>
          <div class="title-name d-inline-block ml-2">{{$t('widget.role_list')}}</div>
        </div>
        <div class="bar d-inline-block float-right">
          <el-button type="primary" size="small" @click="onRoleConfirm">{{$t('btns.confirm')}}</el-button>
          <el-button type="danger" plain size="small" @click="onRoleClean">{{$t('btns.clean')}}</el-button>
          <el-button type="danger" plain size="small" @click="onRoleExit">{{$t('btns.exit')}}</el-button>
        </div>
      </div>
      <!-- 选择角色列表的publicTable -->
      <publicTable ref="publictable_role"
        @handleSelectionChange='handleRoleSelectionChange'
        @handleSizeChange='rolePageSizeChange'
        @handleCurrentChange='roleCurrPageChange'
        @updataParams='updataRoleParams'
        @getData='getRoles'
      ></publicTable>
    </el-dialog>
  </div>
</template>
<script>
import { getWidgets, deleteWidgets,getViewsModuleList,saveWidgets,updateWidgets,getLogoUrl } from "@/service/CommontoolsAPI.js";
import { getAllmodules } from "@/service/CommonApi.js";
import { getChartsList }from "@/service/ModulesApi.js";
import { getSummarysListData }from "@/service/FormApi.js";
import { getReportsList }from "@/service/ReportApi.js";
import publicTable from "@/components/Common/publicTable.vue";
import icon_select from "@/components/Common/icon_select.vue";
import font_select from "@/components/Common/font_select.vue";
import ColorPicker from "@/components/Common/ColorPicker";
import fileUpload from "@/components/Common/fileUpload"
import { nameCheck } from "@/utils/utils.js";
import {delMsg} from '@/utils/elementui'
import { getRoles } from "@/service/CommontoolsAPI.js";
import ScriptEditorSelect from "@/components/Common/scriptEditor";
import config from '@/assets/json/config'
export default {
  name: 'widgetlist',
  data(){
    return{
      params: {
        appId: "",
        id: "",               //widget id
        name: "",             //widget 名称
        type: "",             //类型
        published: "",        //是否发布
        orderno: "",          //排序号
        searchword: "",       //搜索名字
        pageNo: 1,
        linesPerPage: 10
      },
      data: {},
      multipleSelectionId: [],
      multipleSelectionArray: [],
      tableHeight: 100,
      dialogFormVisible: false,       //对话框
      widgetForm: {
        name: "",             //名称
        type: "",             //类型
        authMode: "0",        //授权方式
        widgetType: "0",      //支持类型
        countType: 'none',    // 统计类型
        published: "true",    //是否发布
        moduleid: "",           //模块
        actionView: "",       //作用视图
        chart: "",            //图表
        actionContent: "",    //
        actionSummary: "",    //摘要
        actionUrl: "",        //链接地址URL
        iconShow: false,         //是否常用
        iscript: "",          //Iscript脚本内容
        userScript: "",       // 脚本返回用户对象集合
        width: "",            //宽度
        height: "",           //高度
        authRolesId: "",      //
        authRolesName: "",    //
        icon: "",             //
        titleColor: "#000",   //标题颜色
        titleBColor: null,  //标题背景颜色
        titleBarColor: null,//标题栏颜色
        orderno: "",         //排序号
        frequency: 0,        //频率
        carouselImg: "",      //轮播图图片
      },
      icon: { 
        icontype: "img",
        imgUrl: "/uploads/lib/icon_menu_default.png",
        fontUrl: "",
        iconFontColor: "rgba(0, 0, 0, 1)"
      },
      iconSelectCheck: false, // 图片
      fontSelectCheck: false, // 字体图标
      fontStyle: "", // 字体图标的样式
      rules: {
        name: [
          { required: true, message: this.$t('placeholder.name'), trigger: 'blur'},
          { validator: nameCheck, trigger: "blur" },
        ],
        type: [
          { required: true, message: this.$t('placeholder.select_type'), trigger: 'blur'}
        ],
        orderno: [
          { required: true, message: this.$t('placeholder.into_order_num'), trigger: 'blur'}
        ],
        actionSummary:[
          { required: true, message: this.$t('placeholder.choose_summary'), trigger: 'blur'}
        ],
        customizeReport:[
          { required: true, message: this.$t('msg.select_report'), trigger: 'blur'}
        ],
        actionUrl:[
          { required: true, message: this.$t('placeholder.enter_url'), trigger: 'blur'}
        ],
        iscript:[
          { required: true, message: this.$t('placeholder.enter_script'), trigger: 'blur'}
        ],
      },
      predefineColors:[
        '#000',
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
        'rgba(255, 69, 0, 0.68)',
        'rgb(255, 120, 0)',
        'hsv(51, 100, 98)',
        'hsva(120, 40, 94, 0.5)',
        'hsl(181, 100%, 37%)',
        'hsla(209, 100%, 56%, 0.73)',
        '#c7158577'
      ],
      typeOptions: config.widgetOptions,
      isTypeOptions: {
        isActionSummary: false,     //摘要
        isModule: false,            //模块
        isActionView: false,        //作用视图
        isCustomizeReport: false,   //作用报表
        isChart: false,             //图表
        isActionUrl: false,         //链接地址(URL)
        isIsript: false,     //Iscript脚本内容
      },
      moduleOptions : [],         //模板数组
      actionViewOptions: [],      //作用视图数组
      reportOptions: [],          //报表
      tableData:{params:[{name:'name',label:this.$t('stateLabel.name'),value:"",}]},
      roleVisible:false,
      roleParams: {
        appId: "",
        name: "",             //角色名称
        pageNo: 1,
        linesPerPage: 10
      },
      tableDataRole:{params:[{name:'name',label:this.$t('stateLabel.name'),value:"",}],tableHeight:'350px',},
      checkedRoles:[],
      scriptEditorVisible: false, // 脚本编辑器弹窗
      currentScriptEditor: '', // 当前选中哪一个脚本编辑器
      fileUploadVisible: false, // 图片上传弹窗
      btnLoading: false, // 按钮的加载
    }
  },
  components:{
    publicTable,
    icon_select,
    font_select,
    ColorPicker,
    ScriptEditorSelect,
    fileUpload
  },

  mounted(){
    this.getScollerHeight();
    if(this.$route.query.edit){
      let appId = sessionStorage.getItem("appId");
      let params = {
        ...this.params,
        appId: appId,
      }
      this.params = params;
      this.roleParams.appId = appId;
      this.getWidgets();
    }
  },
  methods:{
    /**
     * 显示脚本编辑器弹框
     */
    showScriptEditor (val) {
      this.scriptEditorVisible = true;
      this.currentScriptEditor = val
    },
    /**
     * 将脚本编辑器的值写入到textarea中
     */
    handleScriptEditor (val) {
      switch (this.currentScriptEditor){
        case "iscript":
          this.widgetForm.iscript = val
          break;
        case "userScript":
          this.widgetForm.userScript = val
          break;
        default:
          break;
      }
    },
    //退出编辑widget
    exitEditDetail(){
      this.dialogFormVisible = false;
      this.checkedRoles=[];
    },
    //退出选择角色弹窗
    onRoleExit(){
      this.roleVisible = false;
    },
    //角色选中确认
    onRoleConfirm(){
    debugger
      let authRolesNames=[];
      let authRolesIds=[];
      this.checkedRoles.map((e) => {
          authRolesNames.push(e.name)
          authRolesIds.push(e.id)
        })
      this.widgetForm.authRolesName = authRolesNames.join(";");
       this.widgetForm.authRolesId = authRolesIds.join(";");
      this.roleVisible = false;
    },
    //清除所选角色
    onRoleClean(){
      this.$refs.publictable_role.clearSelection();
      this.checkedRoles =[];
      this.tableDataRole.checkedRows = this.checkedRoles;
      this.widgetForm.authRolesName =  '';
      this.widgetForm.authRolesId =  '';
    },
    //清除详情中的角色字段
    onRoleClean_detail(){
      this.checkedRoles =[];
      this.tableDataRole.checkedRows = this.checkedRoles;
      this.widgetForm.authRolesName =  '';
      this.widgetForm.authRolesId =  '';
    },
    //角色列表页码变化
    roleCurrPageChange(val){
      let roleParams = {
        ...this.roleParams,
        pageNo: val
      }
      this.roleParams = roleParams;
      this.getRoles()
    },
    //角色列表页大小变化
    rolePageSizeChange(val){
      let roleParams = {
        ...this.roleParams,
        linesPerPage: val
      }
      this.roleParams = roleParams;
      this.getRoles()
    },
    /**
     * 勾选行时响应
     */
    handleRoleSelectionChange(val) {
      this.checkedRoles=[]
      if(val.length){
        val.map((e) => {
          this.checkedRoles.push(e)
        })
      }
      this.tableDataRole.checkedRows = this.checkedRoles;
    },
    //更新参数
    updataRoleParams(obj){
      Object.assign(this.roleParams,obj)
    },
    //获取角色列表
    async getRoles(){
      const response = await getRoles(this.roleParams)
      if (response.data.errcode == 0) {
        let data = response.data.data;

        // 进行数据回选
        if(this.widgetForm.authRolesId != ""){
          let tempArr = this.widgetForm.authRolesId.split(';').filter(item => item != "")
          for(let i = 0; i < tempArr.length; i++){
            for(let j = 0; j < data.datas.length; j++){
              if(data.datas[j].id == tempArr[i]){
                this.checkedRoles.push(data.datas[j])
                break;
              }
            }
          }
        }
        this.tableDataRole.columns=[{prop:'name',label: this.$t('roles.name')}];
        this.tableDataRole.data = data;
        this.tableDataRole.checkedRows =this.checkedRoles

        this.$nextTick(() => {
          this.$refs.publictable_role.init(this.tableDataRole);
        })
      }
    },
    //选择角色
    chooseRole(){
      this.roleVisible = true;
      this.getRoles();
    },
    //更新参数
    updataParams(obj){
      Object.assign(this.params,obj)
    },
    /**
     * 动态计算页面table高度
     */
    getScollerHeight() {
      setTimeout(() => {
        let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        //60 头部， 32 面包屑， 41 第一层页签， 40 第二层页签， 50 列表标题， 71 查询， 20 父组件外边距, 40分页
        this.tableData.tableHeight = (clientHeight - 60 - 32 - 41 - 40 - 50 - 71 - 20 - 40) + 'px';
        this.$nextTick(() => {
          this.$refs.publictable.init(this.tableData);
        })
      }, 100)
    },
    
    /**
     * 获取widget列表
     */
    async getWidgets(){
      let response = await getWidgets(this.params);
      if (response.data.errcode == 0) {
        let data = response.data.data;
        for(let i=0;i<data.datas.length;i++){
          if(data.datas[i].type == "summary"){
            data.datas[i].label = this.$t('widget.summary');
          }else if(data.datas[i].type == "view"){
            data.datas[i].label = this.$t('view.view');
          }else if(data.datas[i].type == "page"){
            data.datas[i].label = this.$t('widget.ual_content');
          }else if(data.datas[i].type == "customizeReport"){
            data.datas[i].label = this.$t('menu.custom_report');
          }else if(data.datas[i].type == "chart"){
            data.datas[i].label = this.$t('widget.chart');
          }else if(data.datas[i].type == "system_workflow"){
            data.datas[i].label = this.$t('form.flow_processing');
          }else if(data.datas[i].type == "iscript"){ 
            data.datas[i].label = this.$t('widget.cal_script');
          }else if(data.datas[i].type == "carboncopy"){
            data.datas[i].label = this.$t('widget.carboncopy');
          }else if(data.datas[i].type == "carousel"){
            data.datas[i].label = this.$t('widget.carousel');
          }else if(data.datas[i].type == "checkin"){
            data.datas[i].label = '签到';
          }
          
          if(data.datas[i].published == true){
            data.datas[i].publishShow = this.$t('widget.yes');
          }else if(data.datas[i].published == false){
            data.datas[i].publishShow = this.$t('widget.no');
          }
        }
        
        this.tableData.columns=[{prop:'name',label: this.$t('widget.name')}, {prop:'label',label: this.$t('widget.type')}, {prop:'publishShow',label: this.$t('widget.publish_or_not')}, {prop:'orderno',label: this.$t('widget.order_number')}];
        this.tableData.data=data;
        console.log(data)
        this.$nextTick(() => {
          this.$refs.publictable.init(this.tableData);
        })
      }
    },

    /**
     * 重置查询名称值
     */
    resetName(){
      let params = {
        ...this.params,
        name: "",
      }
      this.params = params;
      this.getWidgets();
    },

    /**
     * 勾选行时响应
     */
    handleSelectionChange(val) {
      let multipleSelectionId = [];
      if(val.length){
        val.map((e) => {
          multipleSelectionId.push(e.id)
        })
      }
      this.multipleSelectionArray = val;
      this.multipleSelectionId = multipleSelectionId;
    },

    /**
     * 新建widget
     */
    createRoles(){
      this.dialogFormVisible = true;
      let widgetForm = {
        id: "",               //id
        name: "",             //名称
        type: "",             //类型
        authMode: "0",        //授权方式
        widgetType: "0",      //支持类型
        countType: 'none',    // 统计类型
        published: "true",    //是否发布
        moduleid: "",           //模块
        actionView: "",       //作用视图
        chart: "",            //图表
        icontype: "font",     //图标类型
        actionContent: "",    //
        actionSummary: "",    //摘要
        actionUrl: "",        //链接地址URL
        iconShow: false,         //是否常用
        iscript: "",          //Iscript脚本内容
        width: "",            //宽度
        height: "",           //高度
        authRolesId: "",      //
        authRolesName: "",    //
        icon: "",             //
        titleColor: "#000",   //标题颜色
        titleBColor: null,  //标题背景颜色
        titleBarColor: null,//标题栏颜色
        orderno: "",          //排序号
        frequency: 0,        //频率
        carouselImg: "",      //轮播图图片
        imgUrl: "/uploads/lib/icon_menu_default.png",
        fontUrl: "",
        iconFontColor: "rgba(0, 0, 0, 1)"
      }
      // 重置显示的属性
      let isTypeOptions = {
        isActionSummary: false,     //摘要
        isModule: false,            //模块
        isActionView: false,        //作用视图
        isCustomizeReport: false,   //作用报表
        isChart: false,             //图表
        isActionUrl: false,         //链接地址(URL)
        isIsript: false,     //Iscript脚本内容
      }
      this.widgetForm = widgetForm;
      this.isTypeOptions = isTypeOptions;
      // 重置所有的错误消息
      // let params = {
      //   appId: sessionStorage.getItem("appId"),
      // }
      // this.$router.push({path: '/home/softwaresdetails/commontool/roles', query:{edit: false, params: params}});
    },

    /**
     * 删除widget
     */
    async showDeleteConfirm(){
      let params = this.params;
      let multipleSelectionId = this.multipleSelectionId;
      if(multipleSelectionId.length > 0){
        try{
          await delMsg(this.$t('msg.delConfirm'), this.$t('msg.tip'))
          let response = await deleteWidgets(multipleSelectionId, params.appId);
          if (response.data.errcode == 0) {
            this.getWidgets();
            this.$message.success(this.$t('msg.del_ss'));
          }
        }catch(e){
          console.log(e)
        }
      }else{
        this.$message.error(this.$t('msg.check_data'))
      }
    },

    /**
     * 选中数据源回显
     */
    onRowClick(row){
      this.icon = JSON.parse(row.icon)
      // 设置字体图标颜色
      if(this.icon.iconFontColor && this.icon.icontype == 'font'){
        this.$nextTick(() => {
          this.fontStyle = 'color:' + this.icon.iconFontColor
          this.$refs.fontcolor.color = this.icon.iconFontColor
        })
      }
      // 同步数据
      this.widgetForm = {
        ...row,
        authMode: row.authMode + "",  //授权方式
        widgetType:row.widgetType + "",  //支持方式
        published:row.published == true ? "true" : "false",    //是否发布
        icontype:JSON.parse(row.icon).icontype
      }
      this.typeChange(row.type,row);
      this.dialogFormVisible = true;
      // this.$router.push({path: '/home/softwaresdetails/commontool/roles', query:{edit: true, params: params}});
    },
    /**
     * 当前页
     */
    handleCurrentChange(val) {
      let params = {
        ...this.params,
        pageNo: val
      }
      this.params = params;
      this.getWidgets()
    },

    /**
     * 切换分页，每页显示多少条
     */
    handleSizeChange(val){
      let params = {
        ...this.params,
        linesPerPage: val
      }
      this.params = params;
      this.getWidgets()
    },
    /**
     * 选择类型
     */
    async typeChange(val,row){
      let isActionSummary = false;      //摘要
      let isModule = false;             //模块
      let isActionView = false;         //作用视图
      let isCustomizeReport = false;    //作用报表
      let isChart = false;              //图表
      let isActionUrl = false;          //链接地址(URL)
      let isIsript = false;             //Iscript脚本内容
      let appId = sessionStorage.getItem("appId");
      let currentModuleId = "";
      this.widgetForm.moduleid='';
      this.actionViewOptions=[];
      let response, resp;

      switch(val){
        case "summary":     //摘要
          isActionSummary = true;
          getSummarysListData({appId:appId,id:''},{
            onSucess: async response => {
              if (response.data.errcode == 0) {
                let summaryArr = response.data.data.data
                summaryArr.map(item => {
                  if(item.scope == 0){
                    item.showName = item.name + this.$t('widget.todo_summary')
                  }else if(item.scope == 1){
                    item.showName = item.name + this.$t('widget.flow_share')
                  }else if(item.scope == 6){
                    item.showName = item.name + this.$t('widget.flow_carboncopy')
                  }
                })
                this.actionViewOptions = summaryArr;
                // 需要拼接数据才可以
                this.$set(this.widgetForm, 'actionSummary', row.actionContent)
              }
            }
          });
          break;
        case "view":    //视图
          isModule = true;
          isActionView = true;
          response = await getAllmodules(appId, currentModuleId);
          if (response.data.errcode == 0) {
            this.moduleOptions = response.data.data;
            if(row){
              this.widgetForm.moduleid = row.moduleid;
              // this.params.linesPerPage = 100;
              getViewsModuleList(row.moduleid,this.params, {
                onSucess: response => {
                  if (response.data.errcode == 0) {
                    this.actionViewOptions = response.data.data.datas.filter(item => item.type == 1 || item.type == 16)
                    // 判断有当前id就选中，没有就清空数组
                    let flag = false
                    for (let i = 0; i < this.actionViewOptions.length; i++) {
                      if (this.actionViewOptions[i].id == row.actionContent) {
                        flag = true;
                        this.$set(this.widgetForm, 'actionView', row.actionContent)
                        break;
                      }
                    }
                    if (!flag) {
                      this.$set(this.widgetForm, 'actionView', "")
                    }
                  }
                }
              });
            }
          }
          break;
        case "page":        //链接内容
          isActionUrl = true;
          if(row){
            // this.widgetForm.actionUrl = row.actionContent
            this.$set(this.widgetForm, 'actionUrl', row.actionContent)
          }
          break;
        case "customizeReport": //自定义报表
          isModule = true;
          isCustomizeReport = true;
          resp = await  getAllmodules(appId, currentModuleId);
          if (resp.data.errcode == 0) {
            this.moduleOptions = resp.data.data;
            if(row){
              this.widgetForm.moduleid = row.moduleid;
              this.params.moduleId = row.moduleid;
              // this.params.linesPerPage = 100;
              let response = await getReportsList(this.params);
              if (response.data.errcode == 0) {
                this.actionViewOptions = response.data.data.datas;
                this.$set(this.widgetForm, 'customizeReport', row.actionContent)
              }
            }
          }
          break;
        case "chart":       //图表
          isModule = true;
          isChart = true;
          resp = await getAllmodules(appId, currentModuleId);
          if (resp.data.errcode == 0) {
            this.moduleOptions = resp.data.data;
            if(row){
              this.widgetForm.moduleid = row.moduleid;
              this.params.moduleId = row.moduleid;
              // this.params.linesPerPage = 100;
              let response = await getChartsList(this.params);
              if (response.data.errcode == 0) {
                this.actionViewOptions = response.data.data.data;
                // this.widgetForm.chart = row.actionContent
                this.$set(this.widgetForm, 'chart', row.actionContent)
              }
            }
          }
          break;
        case "iscript":     //计算脚本值
          isIsript = true;
          if(row){
            // this.widgetForm.iscript = row.actionContent
            this.$set(this.widgetForm, 'iscript', row.actionContent)
          }
          break;
        default:
          break;
      }
      let isTypeOptions = {
        ...isTypeOptions,
        isActionSummary: isActionSummary,     //摘要
        isModule: isModule,                   //模块
        isActionView: isActionView,           //作用视图
        isCustomizeReport: isCustomizeReport, //作用报表
        isChart: isChart,                     //图表
        isActionUrl: isActionUrl,             //链接地址(URL)
        isIsript: isIsript,                   //Iscript脚本内容
      }
      this.isTypeOptions = isTypeOptions
    },
    /**
     * 获取模块列表--->根据上一级获取
     */
    async moduleChange(val){
      this.params.moduleId = val;
      this.params.linesPerPage = 100000;
      if(this.widgetForm.type == "customizeReport"){
        let response = await getReportsList(this.params);
        if (response.data.errcode == 0) {
          this.actionViewOptions = response.data.data.datas;
        }
      }else if(this.widgetForm.type == "chart"){
        let response = await getChartsList(this.params);
        if (response.data.errcode == 0) {
          this.actionViewOptions = response.data.data.data;
        }
      }else{
        getViewsModuleList(val,this.params, {
          onSucess: response => {
            if (response.data.errcode == 0) {
              this.actionViewOptions = response.data.data.datas
              this.$set(this.widgetForm, 'actionView', "")
            }
          }
        });
      }
    },
    /**
     * 新建保存widget
     */
    save(widgetForm){
      this.$refs[widgetForm].validate(async (valid) => {
        if(valid){
          let appId = sessionStorage.getItem("appId");
          let data = JSON.parse(JSON.stringify(this.widgetForm));
          data.authMode = parseInt(data.authMode);
          data.widgetType = parseInt(data.widgetType);
          data.orderno = parseInt(data.orderno);
          data.published = data.published == "true"? true : false;
          
          // 图片或字体图标
          if(this.icon.icontype == 'img'){
            data.icon = `{"icon":"${this.icon.imgUrl}","icontype":"${this.icon.icontype}", "imgUrl": "${this.icon.imgUrl}"}`
          }else if(this.icon.icontype == 'font'){
            data.icon = `{"icon":"${this.icon.fontUrl}","icontype":"${this.icon.icontype}", "fontUrl":"${this.icon.fontUrl}", "iconFontColor":"${this.icon.iconFontColor}"}`
          }

          // 校验授权给特定角色
          if(this.widgetForm.authMode == 1 && this.widgetForm.authRolesId == ""){
            this.$message.error(this.$t('widget.select_role'))
            return false
          }
          
          if(this.isTypeOptions.isActionView){
            data.actionContent = data.actionView;
          }else if(this.isTypeOptions.isChart){
            data.actionContent = data.chart;
          }else if(this.isTypeOptions.isIsript){
            data.actionContent = data.iscript
          }else if(this.isTypeOptions.isActionUrl){
            data.actionContent = data.actionUrl
          }else if(this.isTypeOptions.isActionSummary){
            data.actionContent = data.actionSummary
          }else if(this.isTypeOptions.isCustomizeReport){
            data.actionContent = data.customizeReport
          }

          // 更新
          if(data.id){
            data.widgetId = data.id
            data.parentId = sessionStorage.getItem("appId")
            this.btnLoading = true
            let response = await updateWidgets(data);
            this.btnLoading = false
            if (response.data.errcode == 0) {
              this.$message.success(this.$t('msg.update_ss'));
              this.dialogFormVisible = false;
              this.getWidgets();
            }
          }else{ // 新建
            this.btnLoading = true
            let response = await saveWidgets(appId,data);
            this.btnLoading = false
            if (response.data.errcode == 0) {
              this.actionViewOptions = response.data.data.datas;
              this.$message.success(this.$t('msg.created_ss'));
              this.dialogFormVisible = false;
              this.getWidgets();
            }
          }
        }else {
          return false;
        }
      });
    },

    /**
     * 重置弹窗信息
     */
    resetWidgetForm(formName) {
      this.icon = {
        imgUrl: "/uploads/lib/icon_menu_default.png",
        fontUrl: "",
        icontype: "img",
        iconFontColor: "rgba(0, 0, 0, 1)"
      };
      this.$nextTick(() => this.$refs[formName].resetFields())
    },

    getLogoUrl (url) {
      return getLogoUrl(url);
    },
    onSelectIconOk (item) {
      if (item) {
        if (item.path) {
          this.widgetForm.icontype = "img";
          this.icon.imgUrl = item.path;
        } else {
          this.$message({
            showClose: true,
            type: "error",
            message: this.$t('msg.select_fail'),
          });
        }
      }
    },
    selectImg () {
      this.iconSelectCheck = true;
    },

    onSelectFontOk (font) {
      this.icon.fontUrl = font
      this.icon.icontype = 'font'
      this.fontSelectCheck = false; 
    },
    selectFont () {
      this.fontSelectCheck = true;
    },

    /**
     * 读取和设置颜色
     */
    setColor(val, name) {
      if(name == 'iconFontColor'){
        this.icon.iconFontColor = val
        // 设置颜色
        this.fontStyle = 'color:' + val
      }else if(name == 'titleColor'){
        this.widgetForm.titleColor = val
      }else if(name == 'titleBColor'){
        this.widgetForm.titleBColor = val
      }else if(name == 'titleBarColor'){
        this.widgetForm.titleBarColor = val
      }
    },

    onCheckUpload(file) {
      if(file){
        this.widgetForm.carouselImg = file[0].filePath
      }
    },
  },
  computed:{
    /**
     * textarea 传给 脚本编辑器的值
     */
    showScritptEditorCode () {
      let code
      if (this.currentScriptEditor === 'iscript') {
        // 表单基本是否可编辑脚本
        code = this.widgetForm.iscript
      }else if(this.currentScriptEditor === 'userScript'){
        // 脚本返回用户对象集合
        code = this.widgetForm.userScript
      }
      return code
    },
    /**
     * 显示 高 标签
     */
    showHeightLabel(){
      let flag = false
      if(this.widgetForm.type == 'chart' || this.widgetForm.type == 'page' || this.widgetForm.type == 'iscript' || this.widgetForm.type == 'carousel'){
        flag = true
      }
      return flag
    },
    /**
     * 显示 频率 标签
     */
    showCarousel(){
      let flag = false
      if(this.widgetForm.type == 'carousel'){
        flag = true
      }
      return flag
    }
  },
}
</script>