<!-- @desc:自定义报表  @auth:周兴  @time:2023/3/26 10:05 -->
<template>
  <div class="main-div" ref="mainDiv">
    <!--加载中-->
    <loading :loading="loading" v-if="!modalVisible"></loading>
    <BaseIndexButtonGroup id="BaseIndexButtonGroup">
      <template #left>
        <!--    查询    -->
        <BaseIndexButton right-button="user-select" ref="search" name="search"></BaseIndexButton>
        <!--    清空条件    -->
        <BaseIndexButton ref="clear" name="clear"></BaseIndexButton>
        <!--    编辑    -->
        <BaseIndexButton right-button="user-edit" ref="edit" name="edit"></BaseIndexButton>
        <!--    发布(只有1工厂才能进行发布)    -->
        <BaseIndexButton right-button="user-publish" ref="publish" name="publish" ></BaseIndexButton>
        <!--    预览    -->
        <BaseIndexButton right-button="user-preview" ref="preview" name="preview"></BaseIndexButton>
        <!--    导出SQL(只有1工厂才能进行导出)    -->
        <BaseIndexButton right-button="user-publish" ref="export" name="export"  :isMustChooseFlag="false"></BaseIndexButton>
        <!--    导入    -->
        <BaseIndexButton right-button="user-add" ref="import" name="import" :isMustChooseFlag="false"></BaseIndexButton>
      </template>
      <template #right>
        <!--   新建     -->
        <BaseIndexButton right-button="user-add" ref="add" name="add"></BaseIndexButton>
      </template>
    </BaseIndexButtonGroup>

    <!--  查询条件区域  -->
    <div id="search-cond-div" ref="search-cond-div" class="search-cond-class">
      <SearchCond ref="searchCond" v-model="searchCond"
                  @collapse-change="collapseChange" :setFlag="false"
                  :searchContent="searchContent"
      ></SearchCond>
    </div>

    <!--  表格部分  -->
    <DkSplit mode="vertical" v-model="split" :height="tableHeight">
      <DkTable slot="top" :id="'table-'+$options.name" ref="table-select" :data="tableData"
               :height="this.tableHeight * split - 35"
               :choose-flag="false"
               :pageFlag="true"
               primaryKey="reportId"
               :page-total="pageInfo.total"
               :current-page="pageInfo.currentPage"
               @pageChange="pageSizeChange"
               @current-change="handleChange">
        <DkTableColumn field="reportName" type="link"
                       @on-link="handleLink(Object.assign($event,{button:'edit'}))"></DkTableColumn>
        <DkTableColumn field="reportStatusName" :color-cards="['发布','暂存']"
                       :title="$t('reportStatusName')"></DkTableColumn>
        <DkTableColumn field="reportTypeName"></DkTableColumn>
        <DkTableColumn field="displayNo"></DkTableColumn>
        <!--        <DkTableColumn field="preview" type="link"-->
        <!--                       @on-link="handleLink(Object.assign($event,{url:'/report/custom-report/report/custom-report-detail-' + $event.reportId}))"></DkTableColumn>-->
        <DkTableColumn field="flgValid" type="switch" @on-switch-change="onSwitchChange"
                       :switch-disabled="false"></DkTableColumn>
        <DkTableColumn field="describe" width="auto"></DkTableColumn>
        <DkTableColumn field="remarks" width="auto"></DkTableColumn>
      </DkTable>

      <div slot="bottom">
        <DkTabs v-model="reportTab" :options="detailOptions" @on-click="changeTab"></DkTabs>
        <!-- 查询条件设置 -->
        <DkTable v-show="reportTab === 'condition'" :pageFlag="false"
                 :pageTotalFlag="false"
                 primaryKey="conditionId"
                 :height="this.tableHeight * (1-split) "
                 :expand-flag="true"
                 :id="'table-'+$options.name"
                 ref="detail-select"
                 :choose-flag="false"
                 :data="conditionList">
          <DkTableColumn field="code"></DkTableColumn>
          <DkTableColumn field="name"></DkTableColumn>
          <DkTableColumn field="kind" :title="$t('reportKind')"></DkTableColumn>
          <DkTableColumn field="sqlScript" ></DkTableColumn>
          <DkTableColumn field="flgRequired" type="switch"></DkTableColumn>
          <DkTableColumn field="defaultValue" ></DkTableColumn>
          <DkTableColumn field="otherCondition" ></DkTableColumn>
          <DkTableColumn field="positionName"></DkTableColumn>
          <DkTableColumn field="displayNo"></DkTableColumn>
          <DkTableColumn field="remarks" width="auto"></DkTableColumn>
        </DkTable>
        <!--sql表格信息-->
        <DkSplit v-show="reportTab === 'sqlSetting'" :height="this.tableHeight * (1-split) ">
          <!--sql-->
          <DkTable slot="left" :pageFlag="false"
                   :pageTotalFlag="false"
                   primaryKey="sqlId"
                   :id="'table-'+$options.name"
                   :height="this.tableHeight * (1-split) "
                   ref="sql-select"
                   :choose-flag="false"
                   :data="sqlList"
                   @current-change="handleSqlChange">
            <DkTableColumn field="name" :title="$t('sqlName')"></DkTableColumn>
            <DkTableColumn field="label" :title="$t('sqlLabel')"></DkTableColumn>
            <DkTableColumn field="flgPage" type="switch"></DkTableColumn>
            <DkTableColumn field="flgProc" type="switch"></DkTableColumn>
            <DkTableColumn field="flgDynamicCol" type="switch"></DkTableColumn>
            <DkTableColumn field="pivot" title="设置透视" type="button" @button-click="settingPivot">
              <template #default="{ row }">
                <div class="vxe-checkbox-class">
                  <vxe-checkbox :disabled="true" v-model="row.flgPivot"></vxe-checkbox>
                </div>
              </template>
            </DkTableColumn>
            <DkTableColumn field="sqlScript" :width="220" type="button" @button-click="showSql" :center-flag="true" :btnBlockFlag="true"></DkTableColumn>
            <DkTableColumn field="displayNo"></DkTableColumn>
            <DkTableColumn field="remarks" width="auto"></DkTableColumn>
          </DkTable>
          <!--表格设置-->
          <DkTable slot="right" :pageFlag="false"
                   :pageTotalFlag="false"
                   primaryKey="tableId"
                   :id="'table-'+$options.name"
                   :height="this.tableHeight * (1-split) "
                   ref="table-setting-select"
                   :choose-flag="false"
                   :data="sqlList[sqlIndex]?.tableSettingList">
            <DkTableColumn field="code"></DkTableColumn>
            <DkTableColumn field="name"></DkTableColumn>
            <DkTableColumn field="width" width="90px"></DkTableColumn>
            <DkTableColumn field="dataType" width="90px"></DkTableColumn>
            <DkTableColumn field="align" width="90px"></DkTableColumn>
            <DkTableColumn field="digits" width="90px"></DkTableColumn>
            <DkTableColumn field="flgThousandth" type="switch" width="90px"></DkTableColumn>
            <DkTableColumn field="flgSum" type="switch" width="90px"></DkTableColumn>
            <DkTableColumn field="flgVisible" type="switch" width="90px"></DkTableColumn>
            <DkTableColumn field="displayNo" width="90px"></DkTableColumn>
            <DkTableColumn field="remarks" width="auto"></DkTableColumn>
          </DkTable>
        </DkSplit>
        <!-- 用户 -->
        <DkTable v-show="reportTab === 'user'" :pageFlag="false"
                 :pageTotalFlag="false"
                 primaryKey="conditionId"
                 :height="this.tableHeight * (1-split) "
                 :expand-flag="true"
                 :id="'table-'+$options.name"
                 ref="detail-select"
                 :choose-flag="false"
                 :data="userList">
          <DkTableColumn field="userCode"></DkTableColumn>
          <DkTableColumn field="userName"></DkTableColumn>
        </DkTable>
      </div>
    </DkSplit>

    <!--输入sql文-->
    <DkModal
      :loading="loading"
      v-model="sqlModal"
      ref="modal_sql"
      @on-visible-change="handleVisibleModal"
      :footer-flag="false"
      :title="$t('sql')"
    >
      <div style="padding-left: 10px;">
        <InputPop v-model="sqlScriptPop" textareaFlag :area-rows="15" :readonly="true"/>
      </div>
    </DkModal>

    <!--选择工厂-->
    <DkModal
      :loading="loading"
      v-model="ftyModal"
      ref="modal_sql"
      @on-visible-change="handleVisibleModal"
      @modalOk="publishOk"
      :title="$t('chooseFty')"
    >
      <DkForm ref="formInline" v-model="formData" :col-count="1">
        <DkFormItem :required="true" prop="ftyIds" :data-type="$config.dataType.array" :label="$t('ftyId')">
          <SelectPop v-model="formData.ftyIds" :multiple="true" :options="ftyList" ref="ftyId"
                     labelKey="ftyName"
                     valueKey="ftyId">
          </SelectPop>
        </DkFormItem>
      </DkForm>
    </DkModal>

    <!--    导入-->
    <Upload v-show="false"
            :headers="{Authorization: 'Bearer ' + $store.state.user.token}"
            :action="this.$config.serviceUrl + $service.customReportService.prefix + $service.customReportService.importSql"
            accept=".sql" :on-success="uploadSuccess"
    >
      <Button ref="uploadButton">
      </Button>
    </Upload>
  </div>
</template>

<script>
import {indexMixin} from "@/mixins";

export default {
  name: "custom-report",
  mixins: [indexMixin],
  data() {
    let self = this
    return {
      sqlModal: false,
      ftyModal: false,
      sqlScriptPop: null,
      tableData: [],
      searchContent: [
        {itemCode: 'reportName'},
        self.$config.flgValidSearch // 有效标识
      ],
      formData: {
        ftyIds: null,
      },
      ftyList: [],// 工厂集合
      conditionList: [],// 条件设置
      sqlList: [],// sql设置
      userList: [],// 用户
      sqlIndex: -1,//
      tableSettingList: [],// 表格设置
      reportTab: 'condition',
      detailOptions: [{label: self.$t('condition'), name: 'condition'}, //查询条件
        {label: self.$t('sqlSetting'), name: 'sqlSetting'},//表格设置
        {label: self.$t('userNames'), name: 'user'},//表格设置
      ],
    }
  },
  methods: {
    /**
     * @desc   : switch停用启用
     * @author : 周兴
     * @date   : 2023/3/29 15:34
     */
    onSwitchChange(param) {
      let params = {
        reportId: param.reportId,
        ftyId: this.$store.state.user.ftyId
      }
      if (param.flgValid) {
        this.excute(this.$service.customReportService, this.$service.customReportService.enableReport, params, true, this.$t('enable'))
      } else {
        this.excute(this.$service.customReportService, this.$service.customReportService.disableReport, params, true, this.$t('disable'))
      }
    },
    /**
     * @desc   : 获取数据
     * @author : 周兴
     * @date   : 2023/3/29 15:34
     */
    getData(params) {
      // 查询数据
      return this.excute(this.$service.customReportService, this.$service.customReportService.selectByCond, params);
    },
    /**
     * @desc   : 发布（只能发布到自己的工厂）
     * @author : 周兴
     * @date   : 2023/4/4 8:28
     */
    publish(rows) {
      // this.getFtyData(rows[0]); // 获取工厂数据
      // this.ftyModal = true;
      this.publishOk();
    },
    /**
     * @desc   : 发布到对应的工厂
     * @author : 周兴
     * @date   : 2023/4/25 15:52
     */
    publishOk() {
      let rows = this.$refs['table-select'].batchRows;
      if(rows && rows.length > 0){
        let params = {
          reportId: rows[0].reportId,
          ftyId: this.$store.state.user.ftyId,
          ftyIds: [],
          reportStatus: this.$config.reportStatus.confirm
        }
        this.loading = true;
        this.excute(this.$service.customReportService, this.$service.customReportService.publishReport,
          params, true, 'publish', false).then(res=>{
            if(res.code === this.$config.SUCCESS_CODE){
              // 关闭窗体
              this.ftyModal = false;
            }
            this.loading = false;
        })
      }
    },
    /**
     * @desc   : 预览
     * @author : 姜宁
     * @date   : 2023/4/7 13:50
     */
    preview(rows) {
      if (rows[0].reportType === this.$config.reportType.app) {
        this.$Message.warning(this.$t('W_134'))
        return
      }
      // if (rows[0].reportStatus === this.$config.reportStatus.temp) {
      //   this.$Message.warning(this.$t('W_135'))
      //   return
      // }
      return this.handleLink(Object.assign(rows[0], {url: '/report/custom-report/report/custom-report-detail-preview-' + rows[0].reportId}))
    },
    /**
     * @desc   : 查看sql
     * @author : 周兴
     * @date   : 2023/3/29 16:54
     */
    showSql(row, rowIndex, field) {
      this.sqlScriptPop = row[field]
      this.sqlModal = true;
    },
    /**
     * @desc   : 行切换
     * @author : 周兴
     * @date   : 2023/3/29 15:32
     */
    handleChange({row}) {
      if (row != null) {
        this.reportTab = 'condition';
        // 查询条件和表格设置
        this.getReportDetail(row.reportId);
      }
    },
    /**
     * @desc   : 切换sql，显示表格设置
     * @author : 周兴
     * @date   : 2023/3/30 16:29
     */
    handleSqlChange({row, rowIndex}) {
      this.sqlIndex = rowIndex;
    },
    /**
     * @desc   : 切换到sql
     * @author : 周兴
     * @date   : 2023/3/30 16:39
     */
    changeTab(val) {
      if (val === 'sqlSetting') {
        this.sqlIndex = 0;
      }
    },
    /**
     * @desc   : 设置透视
     * @author : 周兴
     * @date   : 2023/5/18 14:35
     */
    settingPivot(row){
      this.$router.push(this.$config.routeUrl.customReport.setting.url + '/' + row.reportId + '|' + row.sqlId)
    },
    /**
     * @desc   : 获取明细数据
     * @author : 周兴
     * @date   : 2023/3/29 15:36
     */
    getReportDetail(id) {
      let params = {
        reportId: id,
        scriptFlag: true,
        ftyId: this.$store.state.user.ftyId
      }
      // 查询数据
      this.excute(this.$service.customReportService,
        this.$service.customReportService.selectByReport, params, false).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.conditionList = res.data.conditionList  // 条件设置
          this.sqlList = res.data.sqlList; // sql设置
          this.userList = res.data.userList;// 用户
        }
      })
    },
    /**
     * @desc   : 获取工厂数据
     * @author : 周兴
     * @date   : 2023/4/25 16:16
     */
    getFtyData(rows) {
      this.excute(this.$service.customReportService, this.$service.customReportService.getFtyData,
        {}).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.ftyList = res.data
          this.$nextTick(()=>{
            this.formData.ftyIds = rows.ftyIds
          })
        }
      })
    },
    /**
     * @desc   : 导出SQL
     * @author : 洪旭东
     * @date   : 2023-06-16 10:06
     */
    export () {
      this.excute(this.$service.customReportService, this.$service.customReportService.exportSql,
        {}).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          window.location.href = this.$config.exportSqlUrl
        }
      })
    },
    /**
     * @desc   : 导入
     * @author : 洪旭东
     * @date   : 2023-06-25 13:03
     */
    import () {
      this.$refs.uploadButton.$el.click()
    },
    /**
     * @desc   : 上传成功
     * @author : 洪旭东
     * @date   : 2023-06-25 13:03
     */
    uploadSuccess(res) {
      if (res.code == 200) {
        this.$Message.success(this.$t('I_001', {'param': this.$t('import')}))
      } else {
        this.$Message.error(res.message)
      }
    },
  },

  created() {
    this.primaryKey = 'reportId'  // 设置主键Id
    this.routeObjName = 'customReport'  // 设置路由名称
  }
}
</script>

<style scoped>



/deep/.vxe-checkbox{
  margin-bottom:  0 !important;
  width: 20px;
}


/deep/.vxe-button{
  height: 30px !important;
  line-height: 30px!important;;
  display: flex;
  align-items: center;
  justify-content: center;
}

</style>
