<template>
  <el-dialog
    :visible.sync="dialogVisible"
    class="cv-edit__dialog"
    :before-close="beforeClose"
    fullscreen
    append-to-body
    :show-close="false"
  >
    <template v-slot:title>
      <div class="flex" style="justify-content: space-between">
        <el-page-header @back="close" :content="title"></el-page-header>
        <el-button-group>
          <el-button type="defualt" :disabled="active == 0" @click="back"
            >上一步</el-button
          >
          <el-button type="defualt" :disabled="active == 2" @click="next"
            >下一步</el-button
          >
          <el-button type="primary" @click="submitTemplate">{{
            $t('eip.common.save')
          }}</el-button>
          <el-button
            @click="refresh"
            v-if="formTemplate.dataSourceForm == 'sql'"
            >重置字段</el-button
          >
        </el-button-group>
      </div>
    </template>

    <el-steps :active="active" finish-status="success">
      <el-step title="填写模板基础信息"></el-step>
      <el-step title="配置模板标识符"></el-step>
      <el-step title="上传模板文件"></el-step>
    </el-steps>

    <el-scrollbar class="scrollbar-fullheight">
      <div class="flex step-content" v-if="active === 0">
        <el-form data-vv-scope="form" :model="formTemplate">
          <ht-form-item label="模板名称">
            <ht-input
              v-model="formTemplate.name"
              validate="required"
              width="260px"
              :maxlength="30"
              :showWordLimit="true"
            />
          </ht-form-item>
          <ht-form-item label="模板别名">
            <ht-input
              v-model="formTemplate.alias"
              v-pinyin="formTemplate.name"
              autocomplete="off"
              :validate="{
                required: true,
                alpha_dash: true,
                regex: {
                  exp: '^[\\s\\S]{1,30}$',
                  message: '内容超出输入限制'
                }
              }"
              placeholder="请输入别名"
              :disabled="formTemplate.id ? true : false"
              width="260px"
              :maxlength="30"
              :showWordLimit="true"
            />
          </ht-form-item>
          <ht-form-item label="模板分类" width="260px">
            <EipSysTypeSelector
              placeholder="请选择表单分类"
              cat-id="13"
              v-model="formTemplate.typeName"
              :sys-type-id.sync="formTemplate.typeId"
              :validate="{required: true}"
            />
          </ht-form-item>
          <ht-form-item label="模板描述">
            <ht-input
              v-model="formTemplate.desc"
              type="textarea"
              :rows="5"
              width="260px"
              :maxlength="200"
              :showWordLimit="true"
            />
          </ht-form-item>
          <ht-form-item label="类型">
            <el-radio v-model="formTemplate.printType" label="word"
              >WORD套打</el-radio
            >
            <el-radio v-model="formTemplate.printType" label="excel"
              >EXCEL套打</el-radio
            >
          </ht-form-item>
          <ht-form-item label="数据来源">
            <el-radio v-model="formTemplate.dataSourceForm" label="bo"
              >数据建模</el-radio
            >
            <el-radio v-model="formTemplate.dataSourceForm" label="sql"
              >SQL</el-radio
            >
          </ht-form-item>

          <ht-form-item
            label="选择模型"
            v-if="formTemplate.dataSourceForm == 'bo'"
          >
            <ht-select
              clearable
              filterable
              multiple
              @change="getBoDefData()"
              v-model="formTemplate.boDefIds"
              :options="boList"
              :props="{key: 'id', value: 'description'}"
            />
          </ht-form-item>

          <div v-if="formTemplate.dataSourceForm == 'sql'">
            <ht-form-item label="数据源">
              <ht-select
                :validate="{required: true}"
                v-model="formTemplate.dataSource"
                :options="dataSources"
                :props="{key: 'alias', value: 'name'}"
              />
              <!--              &nbsp;&nbsp;<el-button @click="generateSql">SQL生成</el-button>-->
            </ht-form-item>
            <div v-for="(item,index) in formTemplate.mainSqlList" :key="index">
              <ht-form-item label="sql语句">
                <ht-input
                  type="textarea"
                  :validate="{required: true}"
                  v-model="item.mainSql"
                  :autosize="{minRows: 10, maxRows: 10}"
                />
                &nbsp;&nbsp;<el-button
                  type="primary"
                  @click="checkSql(item.mainSql, formTemplate.dataSource)"
                  >验证SQL</el-button
                >
                &nbsp;&nbsp;<el-button type="primary" @click="addSubSql(item)"
                  >添加一对多SQL</el-button
                >
              </ht-form-item>

              <div v-for="(subsql,idx) in item.subSQList" :key="idx">
                <ht-form-item label="子表名称">
                  <ht-input
                    v-model="subsql.name"
                    @blur="changeSQL(subsql)"
                    :validate="{required: true}"
                    :maxlength="30"
                    :showWordLimit="true"
                  />
                </ht-form-item>
                <ht-form-item label="子表别名">
                  <ht-input
                    v-model="subsql.alias"
                    :validate="{required: true}"
                    :maxlength="30"
                    :showWordLimit="true"
                  />
                </ht-form-item>
                <ht-form-item label="子表sql语句">
                  <ht-input
                    type="textarea"
                    :validate="{required: true}"
                    v-model="subsql.sql"
                    :autosize="{minRows: 10, maxRows: 10}"
                  />
                  &nbsp;&nbsp;<el-button
                    type="primary"
                    @click="checkSql(subsql.sql, formTemplate.dataSource)"
                    >验证SQL</el-button
                  >
                  &nbsp;&nbsp;<el-button
                    type="danger"
                    @click="item.subSQList.remove(subsql)"
                    >删除</el-button
                  >
                </ht-form-item>
              </div>
            </div>
          </div>
        </el-form>
      </div>

      <div v-if="active === 1">
        <el-card class="box-card print-card">
          <div slot="header" class="clearfix">
            <span>模板附件</span>
          </div>
          <input type="hidden" v-model="filesValue" :name="inputName" />
          <file-upload
            ref="fileUpload"
            v-model="files"
            :action-url="actionUrl"
            :multiple="false"
            :accept="fileAccept"
            :before-upload="beforeAvatarUpload"
            :on-success="uploadSuccess"
            :on-error="onError"
            :header="header"
            :size="fileSizeMax"
            :showFiledList="false"
            :limit="1"
            :withCredentials="withCredentials"
            :filesData="filesData"
          >
          </file-upload>
          <!-- <slot slot="append" name="append"> -->
          <span>
            <el-tooltip
              placement="top"
              effect="light"
              v-if="formTemplate.printType == 'word'"
            >
              <div slot="content">附件格式支持：docx</div>
              <el-tooltip effect="light">
                <div slot="content">
                  <p>
                    <span class="word-template-state">主表字段设置</span>
                  </p>
                  <table cellspacing="0" cellpadding="0" width="100%">
                    <tbody>
                      <tr class="firstRow">
                        <td width="294" valign="top" style="padding: 0px">
                          <p>
                            <span class="word-template-state">姓名</span
                            ><span class="word-template-state">:</span>
                            <strong>{{ signStart }}</strong
                            ><span class="word-template-state"
                              >xm<strong>{{ signEnd }}</strong></span
                            >
                          </p>
                          <p>
                            <span class="word-template-state">客户 ID:</span>
                            <strong>{{ signStart }}</strong
                            ><span class="word-template-state"
                              >id_<strong>{{ signEnd }}</strong></span
                            >
                          </p>
                        </td>
                        <td width="66" valign="top" style="padding: 0px"></td>
                        <td width="360" valign="top" style="padding: 0px">
                          年龄:<strong>{{ signStart }}</strong
                          >nl<strong>{{ signEnd }}</strong
                          >&nbsp;
                          <p>
                            出生日期:<strong>{{ signStart }}</strong
                            >csrq<strong>{{ signEnd }}</strong>
                          </p>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                  <p>
                    <br />
                  </p>
                  <p>
                    <span class="word-template-state">子表字段设置：</span>
                  </p>
                  <p>
                    <span class="word-template-state">建模关系为一对多：</span>
                  </p>
                  <table cellspacing="0" cellpadding="0" width="54">
                    <tbody>
                      <tr class="firstRow">
                        <td
                          width="100"
                          colspan="3"
                          valign="top"
                          style="
                            border: 1px solid rgb(166, 166, 166);
                            background: rgb(242, 242, 242);
                            padding: 0px 5px;
                            word-break: break-all;
                          "
                        >
                          <p>
                            <strong
                              ><span class="word-template-state">{{
                                signStart
                              }}</span></strong
                            ><span class="word-template-state"
                              >sub_zsttest{{ signEnd }}</span
                            ><span class="word-template-state">子实体test</span>
                          </p>
                        </td>
                      </tr>
                      <tr>
                        <td
                          width="33"
                          valign="top"
                          style="
                            border-right: 1px solid rgb(166, 166, 166);
                            border-bottom: 1px solid rgb(166, 166, 166);
                            border-left: 1px solid rgb(166, 166, 166);
                            border-image: initial;
                            border-top: none;
                            background: rgb(242, 242, 242);
                            padding: 0px 5px;
                          "
                        >
                          <p>
                            <span class="word-template-state">字段1</span>
                          </p>
                        </td>
                        <td
                          width="33"
                          valign="top"
                          style="
                            border-top: none;
                            border-left: none;
                            border-bottom: 1px solid rgb(166, 166, 166);
                            border-right: 1px solid rgb(166, 166, 166);
                            background: rgb(242, 242, 242);
                            padding: 0px 5px;
                          "
                        >
                          <p>
                            <span class="word-template-state">字段2</span>
                          </p>
                        </td>
                        <td
                          width="33"
                          valign="top"
                          style="
                            border-top: none;
                            border-left: none;
                            border-bottom: 1px solid rgb(166, 166, 166);
                            border-right: 1px solid rgb(166, 166, 166);
                            background: rgb(242, 242, 242);
                            padding: 0px 5px;
                          "
                        >
                          <p>
                            <span class="word-template-state">字段3</span>
                          </p>
                        </td>
                      </tr>
                      <tr>
                        <td
                          width="33"
                          valign="top"
                          style="
                            border-right: 1px solid rgb(166, 166, 166);
                            border-bottom: 1px solid rgb(166, 166, 166);
                            border-left: 1px solid rgb(166, 166, 166);
                            border-image: initial;
                            border-top: none;
                            padding: 0px 5px;
                          "
                        >
                          <p style="text-align: left">
                            <span class="word-template-state">{</span
                            ><span class="word-template-state">sub_zsttest</span
                            ><span class="word-template-state">.zd1}</span>
                          </p>
                        </td>
                        <td
                          width="33"
                          valign="top"
                          style="
                            border-top: none;
                            border-left: none;
                            border-bottom: 1px solid rgb(166, 166, 166);
                            border-right: 1px solid rgb(166, 166, 166);
                            padding: 0px 5px;
                          "
                        >
                          <p>
                            <span class="word-template-state">{</span
                            ><span class="word-template-state">sub_zsttest</span
                            ><span class="word-template-state">.zd2}</span>
                          </p>
                        </td>
                        <td
                          width="33"
                          valign="top"
                          style="
                            border-top: none;
                            border-left: none;
                            border-bottom: 1px solid rgb(166, 166, 166);
                            border-right: 1px solid rgb(166, 166, 166);
                            padding: 0px 5px;
                          "
                        >
                          <p>
                            <span class="word-template-state">{</span
                            ><span class="word-template-state">sub_zsttest</span
                            ><span class="word-template-state">.zd3}</span>
                          </p>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                  <p>
                    <span class="word-template-state">建模关系为一对一：</span>
                  </p>
                  <p>
                    <span class="word-template-state"
                      >字段一： {{ signStart }}</span
                    ><span class="word-template-state"
                      >sub_zsttest.zd1{{ signEnd }}</span
                    >
                    <span class="word-template-state" style="margin-left: 15px"
                      >字段二： {{ signStart }}</span
                    ><span class="word-template-state"
                      >sub_zsttest.zd2{{ signEnd }}</span
                    >
                  </p>
                  <p>
                    <span style="color: red">
                      常用标签类型：文本（{{ signStart }}var{{
                        signEnd
                      }}）、图片（{{ signStart }}var{{ signEnd }}）、富文本（{{
                        signStart
                      }}+var{{ signEnd }}）、印章（{{ signStart }}#signet_var{{
                        signEnd
                      }}）
                      <br />
                      在模板标签中使用SpringEL表达式：方法调用，转大写（{{
                        signStart
                      }}name.toUpperCase(){{ signEnd }}）、条件（{{
                        signStart
                      }}name == 'poi-tl'{{ signEnd }}）、三目运算（{{
                        signStart
                      }}sex ? '男' : '女'{{ signEnd }} ）、运算符（{{
                        signStart
                      }}price/10000 + '万元'{{
                        signEnd
                      }}）、数组列表使用下标访问（{{ signStart }}dogs[0].name{{
                        signEnd
                      }}）
                    </span>
                  </p>
                  <p>
                    <span style="color: red">
                      注意：图片、签章控件按文本标签方式设置
                    </span>
                  </p>
                </div>
                <i class="icon-question" style="margin-left: 8px"
                  >word模板说明</i
                >
              </el-tooltip>
            </el-tooltip>
            <el-button
              style="margin-left: 15px"
              v-if="formTemplate.printType == 'word'"
              icon="el-icon-download"
              @click="downloadWordTemplate()"
              >Word模板下载</el-button
            >
            <el-tooltip
              placement="top"
              effect="light"
              v-if="formTemplate.printType == 'excel'"
            >
              <div slot="content">附件格式支持：xlsx</div>
              <el-tooltip effect="light">
                <div slot="content">
                  <p>
                    <span class="word-template-state">主表字段设置</span>
                  </p>
                  <table
                    cellspacing="1"
                    border="0"
                    cellpadding="0"
                    bgcolor="#888"
                    width="100%"
                  >
                    <tbody>
                      <tr class="firstRow" bgcolor="#FFFFFF">
                        <td
                          width="180"
                          valign="top"
                          style="height: 35px; line-height: 35px"
                        >
                          姓名
                        </td>
                        <td
                          width="180"
                          valign="top"
                          style="height: 35px; line-height: 35px"
                        >
                          <strong>{{ signStart }}</strong
                          ><span class="word-template-state"
                            >xm<strong>{{ signEnd }}</strong></span
                          >
                        </td>
                        <td width="180">客户ID</td>
                        <td width="180">
                          <strong>{{ signStart }}</strong
                          ><span class="word-template-state"
                            >id_<strong>{{ signEnd }}</strong></span
                          >
                        </td>
                      </tr>
                      <tr class="firstRow" bgcolor="#FFFFFF">
                        <td
                          width="180"
                          valign="top"
                          style="height: 35px; line-height: 35px"
                        >
                          年龄
                        </td>
                        <td
                          width="180"
                          valign="top"
                          style="height: 35px; line-height: 35px"
                        >
                          <strong>{{ signStart }}</strong
                          ><span class="word-template-state"
                            >nl<strong>{{ signEnd }}</strong></span
                          >
                        </td>
                        <td width="180">出生日期</td>
                        <td width="180">
                          <strong>{{ signStart }}</strong
                          ><span class="word-template-state"
                            >csrq<strong>{{ signEnd }}</strong></span
                          >
                        </td>
                      </tr>
                    </tbody>
                  </table>
                  <p>
                    <br />
                  </p>
                  <p>
                    <span class="word-template-state">子表字段设置：</span>
                  </p>
                  <table cellspacing="0" cellpadding="0" width="100%">
                    <tbody>
                      <tr>
                        <td
                          width="180"
                          valign="top"
                          style="
                            border-right: 1px solid rgb(166, 166, 166);
                            border-bottom: 1px solid rgb(166, 166, 166);
                            border-left: 1px solid rgb(166, 166, 166);
                            border-image: initial;
                            border-top: none;
                            background: rgb(242, 242, 242);
                            padding: 0px 5px;
                          "
                        >
                          <p>
                            <span class="word-template-state">字段1</span>
                          </p>
                        </td>
                        <td
                          width="180"
                          valign="top"
                          style="
                            border-top: none;
                            border-left: none;
                            border-bottom: 1px solid rgb(166, 166, 166);
                            border-right: 1px solid rgb(166, 166, 166);
                            background: rgb(242, 242, 242);
                            padding: 0px 5px;
                          "
                        >
                          <p>
                            <span class="word-template-state">字段2</span>
                          </p>
                        </td>
                        <td
                          width="180"
                          valign="top"
                          style="
                            border-top: none;
                            border-left: none;
                            border-bottom: 1px solid rgb(166, 166, 166);
                            border-right: 1px solid rgb(166, 166, 166);
                            background: rgb(242, 242, 242);
                            padding: 0px 5px;
                          "
                        >
                          <p>
                            <span class="word-template-state">字段3</span>
                          </p>
                        </td>
                      </tr>
                      <tr>
                        <td
                          width="180"
                          valign="top"
                          style="
                            border-right: 1px solid rgb(166, 166, 166);
                            border-bottom: 1px solid rgb(166, 166, 166);
                            border-left: 1px solid rgb(166, 166, 166);
                            border-image: initial;
                            border-top: none;
                            padding: 0px 5px;
                          "
                        >
                          <p style="text-align: left">
                            <span class="word-template-state"
                              >{{ signStart }}$fe: sub_zsttest</span
                            ><span class="word-template-state"
                              >&nbsp;t.zd1</span
                            >
                          </p>
                        </td>
                        <td
                          width="180"
                          valign="top"
                          style="
                            border-top: none;
                            border-left: none;
                            border-bottom: 1px solid rgb(166, 166, 166);
                            border-right: 1px solid rgb(166, 166, 166);
                            padding: 0px 5px;
                          "
                        >
                          <p>
                            <span class="word-template-state">t.zd2</span>
                          </p>
                        </td>
                        <td
                          width="180"
                          valign="top"
                          style="
                            border-top: none;
                            border-left: none;
                            border-bottom: 1px solid rgb(166, 166, 166);
                            border-right: 1px solid rgb(166, 166, 166);
                            padding: 0px 5px;
                          "
                        >
                          <p>
                            <span class="word-template-state">t.zd3&nbsp;</span>
                            {{ signEnd }}
                          </p>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                  <p>
                    <span style="color: red"
                      >Excel套打使用Easypoi插件，模板的更多玩法和详细配置请参考其官网。</span
                    >
                  </p>
                  <p>
                    <span style="color: red">
                      注意：只支持文本内容套打，不支持图片、签章、富文本等特殊内容套打。
                    </span>
                  </p>
                </div>
                <i class="icon-question" style="margin-left: 8px"
                  >Excel模板说明</i
                >
              </el-tooltip>
            </el-tooltip>
          </span>
          <el-button
            style="margin-left: 15px"
            v-if="formTemplate.printType == 'excel'"
            icon="el-icon-download"
            @click="downloadExcelTemplate()"
            >Excel模板下载</el-button
          >
          <!-- </slot> -->
          <ht-field-tail
            :writeable.sync="writeable"
            :fieldName="inputName"
            :inputValue="filesValue"
          />

          <el-table
            v-if="filesData && filesData.length > 0"
            :data="filesData"
            border
            style="width: 98%; margin-top: 10px; overflow: hidden"
            size="medium"
          >
            <el-table-column
              label="序号"
              align="center"
              type="index"
              width="70"
            ></el-table-column>
            <el-table-column
              label="附件名称"
              prop="name"
              align="center"
              width="350"
            ></el-table-column>
            <el-table-column align="center" label="状态" width="120">
              <template #default="{row: {size, status}}">
                <el-progress
                  type="circle"
                  :width="25"
                  :percentage="size > 0 ? 100 : 0"
                  :stroke-width="2"
                  :status="status == 'success' ? 'success' : 'exception'"
                ></el-progress>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="260">
              <template slot-scope="scope">
                <el-button
                  v-if="false"
                  :type="getRuleState(scope.row.rule)"
                  @click="editTemplateRule(scope.row)"
                  size="small"
                  title="授权"
                  icon="el-icon-view"
                  plain
                >
                </el-button>
                <el-button
                  @click="download(scope.row)"
                  size="small"
                  icon="el-icon-download"
                  plain
                >
                </el-button>
                <el-button
                  @click="removeFile(scope.row)"
                  type="danger"
                  size="small"
                  icon="el-icon-delete"
                  plain
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <template v-if="formTemplate.dataSourceForm == 'sql'">
          <el-card
            class="box-card"
            v-for="item in formTemplate.mainSqlList"
            :key="item.id"
          >
            <div slot="header" class="clearfix">
              <span>{{ item.desc }}</span>
              <span style="margin-right: 3px">流程实例ID对应字段:</span>
              <el-select v-model="item.mainInstId" placeholder="请选择">
                <el-option
                  v-for="obj in item.labelConfigs"
                  :key="obj.name"
                  :label="obj.comment"
                  :value="obj.name"
                >
                </el-option>
              </el-select>
            </div>

            <div v-if="item.labelConfigs && item.labelConfigs.length > 0">
              <table class="table table-bordered">
                <tr>
                  <th width="150">列名</th>
                  <th width="250">描述</th>
                  <th width="150">标签</th>
                </tr>
                <tr v-for="obj in item.labelConfigs" :key="obj.id">
                  <td width="150">{{ obj.name }}</td>
                  <td width="250">
                    <el-input v-model="obj.comment" size="mini" />
                  </td>
                  <td width="150">
                    <span>{{</span>{{ obj.name }}<span>}}</span>
                  </td>
                </tr>
              </table>
            </div>
            <template v-if="item.subSQList">
              <div v-for="obj in item.subSQList" :key="obj.id">
                <div style="margin-bottom: 10px">
                  <span
                    style="
                      font-weight: 700;
                      font-size: 15px;
                      margin-right: 40px;
                    "
                    >{{ obj.name }} -<span>子表别名 {</span>{{ obj.alias
                    }}<span>}</span>
                  </span>
                  <span>
                    <span style="margin-right: 5px">子表主键:</span>
                    <el-select v-model="obj.subFk_" placeholder="请选择">
                      <el-option
                        v-for="labelConfigs in obj.labelConfigs"
                        :key="labelConfigs.name"
                        :label="labelConfigs.comment"
                        :value="labelConfigs.name"
                      >
                      </el-option>
                    </el-select>

                    <span style="margin-right: 5px">值来源:</span>
                    <el-select v-model="obj.subFk_Value" placeholder="请选择">
                      <el-option
                        v-for="labelConfigs in item.labelConfigs"
                        :key="labelConfigs.name"
                        :label="labelConfigs.comment"
                        :value="labelConfigs.name"
                      >
                      </el-option>
                    </el-select>
                  </span>
                </div>

                <table class="table table-bordered">
                  <tr>
                    <th width="150">列名</th>
                    <th width="250">描述</th>
                    <th width="150">标签</th>
                  </tr>

                  <tr v-for="obj1 in obj.labelConfigs" :key="obj1.id">
                    <td width="150">{{ obj1.name }}</td>
                    <td width="250">
                      <el-input v-model="obj1.comment" size="mini" />
                    </td>
                    <td width="150">
                      <span>{</span>{{ obj.alias }}.{{ obj1.name
                      }}<span>}</span>
                    </td>
                  </tr>
                </table>
              </div>
            </template>
          </el-card>
        </template>

        <template v-else>
          <el-card
            class="box-card"
            v-for="item in formTemplate.labelConfigs"
            :key="item.id"
          >
            <div slot="header" class="clearfix">
              <span>{{ item.desc }}(复制下表中的标签到模板中占位即可)</span>
            </div>
            <div v-for="(item1, index1) in item.children" :key="index1">
              <table
                class="table table-bordered"
                v-if="item1.nodeType == 'field'"
              >
                <tr v-if="index1 === 0">
                  <th width="150">列名</th>
                  <th width="250">描述</th>
                  <th width="150">标签</th>
                </tr>
                <tr>
                  <td width="150">{{ item1.name }}</td>
                  <td width="250">
                    {{ item1.comment }}
                  </td>
                  <td width="150">
                    <span>{{</span>{{ item1.name
                    }}<span>}}</span>
                  </td>
                </tr>
              </table>

              <div style="margin-bottom: 10px" v-if="item1.nodeType == 'sub'">
                <span style="font-weight: 700; font-size: 15px">{{
                  item1.desc
                }}</span>
                -<span>子表别名 {{</span>{{ item1.nodeType }}_{{ item1.name
                }}<span>}}</span>
                <table class="table table-bordered">
                  <tr>
                    <th width="150">列名</th>

                    <th width="250">描述</th>
                    <th width="150">标签</th>
                  </tr>
                  <tr
                    v-for="(item2, index) in item1.children.filter(
                      item => item.nodeType == 'field'
                    )"
                    :key="index"
                  >
                    <td width="150">{{ item2.name }}</td>
                    <td width="250">
                      {{ item2.comment }}
                    </td>
                    <td width="150">
                      <span>{</span>{{ item1.nodeType }}_{{ item1.name }}.{{
                        item2.name
                      }}<span>}</span>
                    </td>
                  </tr>
                </table>
              </div>
            </div>
          </el-card>
        </template>
      </div>

      <div class="print-card" v-if="active === 2">
        <el-card class="box-card print-card">
          <div slot="header" class="clearfix">
            <span>模板脚本(无个性化判断需求可忽略该步骤)</span>
          </div>
          <table class="form-table" cellspacing="0" cellpadding="0" border="0">
            <tbody>
              <tr>
                <th width="130px">脚本描述:</th>
                <td>
                  <label
                    >此处编写Groovy脚本
                    脚本在生成word前先执行,用于替换打印的值(比如实际值为1或者2,想显示的值为男与女,用java
                    脚本进行判断处理)。<br />
                    可用变量：boMap，该变量中的key为属性字段名，可通过脚本添加键值对或修改map中的值，如：boMap.put("sex","男")</label
                  >
                </td>
              </tr>
              <tr>
                <th width="130px">脚本内容:</th>
                <td>
                  <eip-script-dialog
                    ref="printScriptDialog"
                    v-model="formTemplate.scriptStr"
                    append-to-body
                  />
                  <el-button @click="showScriptDialog()">常用脚本</el-button>

                  <el-button
                    @click="showConditionBuild"
                    v-if="formTemplate.dataSourceForm == 'bo'"
                    size="small"
                    >条件脚本</el-button
                  >
                  <FormPrintTemplateVarSelector
                    style="margin-left: 10px"
                    v-if="formTemplate.dataSourceForm == 'bo'"
                    :varData="boDefData"
                    @node-click="varTreeOnConfirm"
                  /><br /><br />
                  <codemirror
                    ref="mycode"
                    v-model="formTemplate.scriptStr"
                    :options="printScriptOptions"
                    class="code"
                    style="width: 99%"
                  ></codemirror>
                </td>
              </tr>
            </tbody>
          </table>
        </el-card>
      </div>

      <FormPrintTemplateRuleCondition
        :varData="boDefData"
        @formPrintTemplateConditionConfirm="conditionConfirm"
        ref="FormPrintTemplateRuleCondition"
      />
      <FormPrintTemplateSqlRuleDialog
        :metafields="labelConfigs"
        @onConfirm="conditionConfirm"
        ref="FormPrintTemplateSqlRuleDialog"
      />
      <FormPrintTemplateConditionBuildDialog
        @onConfirm="conditionDialogConfirm"
        :varData="boDefData"
        ref="flowConditionBuildDialog"
      />
    </el-scrollbar>
  </el-dialog>
</template>

<script>
// word套打配置
import request from '@/request.js'
import form from '@/api/form'
import deepmerge from 'deepmerge'
import {mapState} from 'vuex'
import portal from '@/api/portal'
const FileUpload = () => import('@/components/common/FileUpload.vue')
const EipSysTypeSelector = () =>
  import('@/components/selector/EipSysTypeSelector.vue')
const FormPrintTemplateRuleCondition = () =>
  import('@/components/form/FormPrintTemplateRuleCondition.vue')
const FormPrintTemplateSqlRuleDialog = () =>
  import('@/components/form/FormPrintTemplateSqlRuleDialog.vue')
const FormPrintTemplateVarSelector = () =>
  import('@/components/form/FormPrintTemplateVarSelector.vue')
const FormPrintTemplateConditionBuildDialog = () =>
  import('@/components/form/FormPrintTemplateConditionBuildDialog.vue')
const eipScriptDialog = () => import('@/components/dialog/EipScriptDialog.vue')
export default {
  name: 'FormWordConfig',
  components: {
    FileUpload,
    EipSysTypeSelector,
    FormPrintTemplateRuleCondition,
    FormPrintTemplateSqlRuleDialog,
    FormPrintTemplateVarSelector,
    eipScriptDialog,
    FormPrintTemplateConditionBuildDialog
  },
  data() {
    return {
      dialogVisible: false,
      title: '编辑套打信息',
      tabPane: 'dataSource',
      formTemplate: {
        alias: '',
        boDefIds: '',
        fileId: '',
        fileName: '',
        formKey: '',
        printType: 'word',
        dataSource: 'LOCAL',
        labelConfigs: [],
        mainSqlList: [
          {
            mainSql: '',
            mainInstId: '',
            subSQList: []
          }
        ],
        mainSql: '',
        dataSourceForm: 'bo',
        scriptStr: ''
      },
      formId: '',
      boDefId: '',
      boDefData: {},
      varData: [],
      defaultProps: {
        children: 'children',
        label: 'desc'
      },
      dataSources: [],
      componentType: 'add',
      active: 0,
      boList: [],
      files: [],
      filesValue: '',
      withCredentials: false,
      writeable: true,
      inputName: null,
      filesData: [],
      editFile: null,
      fileAccept: '.docx',
      fileSizeMax: 50,
      labelConfigs: [],
      conditionReplaceChar: ' &@ ',
      signStart: '{{',
      signEnd: '}}',
      printScriptOptions: {
        value: '',
        mode: 'groovy',
        readOnly: false,
        smartIndent: true,
        tabSize: 1,
        theme: 'base16-light',
        lineNumbers: true,
        line: true
      }
    }
  },
  computed: {
    ...mapState({
      currentUser: state => state.login.currentUser,
      header: state => {
        return {Authorization: `Bearer ${state.login.currentUser.token}`}
      },
      actionUrl: function() {
        return `${window.context.portal}/system/file/v1/upload`
      },
      formDeleteUrl: function() {
        return `${window.context.form}/form/printTemplate/v1/removes`
      }
    })
  },
  mounted() {
    form.getDataSource().then(resp => {
      this.dataSources = resp.data
    })
  },
  created() {
    this.$validator = this.$root.$validator
    this.inputName = Math.random()
      .toString(36)
      .substr(2, 10)
  },
  watch: {
    boDefData: {
      handler(val) {
        if (val && val.children) {
          this.setBoDefId(val)
        }
      },
      immediate: true
    },
    // 'formTemplate.boDefIds': {
    //   handler(val) {
    //     if (!val && this.boDefData && this.boDefData.children) {
    //       this.setBoDefId(this.boDefData)
    //     }
    //   },
    //   immediate: true
    // },
    filesData: function(newVal) {
      this.initFileJson(newVal)
    },
    files: function(newVal) {
      if (typeof newVal === 'string') {
        this.filesData = [...this.filesData, ...JSON.parse(newVal)]
      }
    },
    'formTemplate.printType': function(newVal, oldVal) {
      if (newVal === 'excel') {
        this.fileAccept = '.xlsx'
      } else {
        this.fileAccept = '.docx'
      }
      if (oldVal && newVal != oldVal) {
        if (this.formTemplate.fileJson) {
          this.$message.warning(
            '模板文件类型变更，与之前上传模板附件类型不一致，模板附件数据清除。'
          )
          this.formTemplate.fileJson = ''
        }
      }
    }
  },
  methods: {
    setBoDefId(val) {
      const ids = []
      val.children.forEach(item => {
        ids.push(item.boDefId)
      })
      this.formTemplate.boDefIds = ids.join(',')
    },
    initFileJson(newVal) {
      let r = ''
      if (newVal && newVal.constructor === Array && newVal.length > 0) {
        // 只有上传成功的附件才能更新v-model值
        let ary = newVal.filter(m => m.status === 'success')
        if (ary && ary.length > 0) {
          r = JSON.stringify(ary)
        }
      }
      this.formTemplate.fileJson = r
    },
    handleOpen(wordId) {
      this.active = 0
      this.formTemplate = {}
      this.filesData = []
      this.files = []
      this.boDefData = []
      this.labelConfigs = []
      this.initBoList()
      if (wordId) {
        this.componentType = 'update'
        request.get('${form}/form/printTemplate/v1/' + wordId).then(resp => {
          this.formTemplate = resp.data
          if (resp.data.labelConfigs) {
            this.formTemplate.labelConfigs = JSON.parse(resp.data.labelConfigs)
          } else {
            this.formTemplate.labelConfigs = []
          }
          if (resp.data.mainSqlList) {
            this.formTemplate.mainSqlList = JSON.parse(resp.data.mainSqlList)
          } else {
            this.formTemplate.mainSqlList = [
              {mainSql: '', mainInstId: '', subSQList: []}
            ]
          }
          if (resp.data.dataSourceForm == 'bo' && resp.data.boDefIds) {
            this.getBoDefData()
          }
          this.dialogVisible = true
        })
      } else {
        this.componentType = 'add'
        this.formTemplate = {
          alias: '',
          typeId: '31123',
          typeName: '默认分类',
          fileId: '',
          fileName: '',
          formKey: '',
          printType: 'word',
          dataSource: 'LOCAL',
          labelConfigs: [],
          mainSqlList: [
            {
              mainSql: '',
              mainInstId: '',
              subSQList: []
            }
          ],
          mainSql: '',
          dataSourceForm: 'bo',
          scriptStr: ''
        }
        this.dialogVisible = false
        this.$nextTick(() => {
          this.dialogVisible = true
        })
      }
    },
    async next() {
      if (this.active === 0 && this.formTemplate.dataSourceForm == 'sql') {
        let diySql = []
        this.formTemplate.mainSqlList.forEach(obj => {
          diySql.push(obj.mainSql)
          if (obj.subSQList) {
            obj.subSQList.forEach(r => {
              diySql.push(r.sql)
            })
          }
        })
        let data = {
          sql: diySql,
          dsName: this.formTemplate.dataSource,
          isBatch: true
        }
        if (!diySql) {
          this.$message('请填写自定义sql!')
          return
        }
        let res = await form.checkSql(data)
        if (!res.state) {
          return
        }
      }
      if (
        this.formTemplate.dataSourceForm == 'bo' &&
        !this.formTemplate.boDefIds
      ) {
        this.$message.error('选择模型不能为空！')
        return
      }
      if (this.active < 2) {
        if (
          this.active == 1 &&
          this.formTemplate.dataSourceForm == 'sql' &&
          !this.formTemplate.mainSqlList[0].mainInstId
        ) {
          this.$message.error('请设置流程实例ID对应字段！')
          this.active = 1
          return
        }
        this.active++
        if (this.active == 1) {
          this.leaveTabVerify()
          if (this.componentType == 'add') {
            // this.getData()
          }
        }
      }
      if (this.active == 1 && this.formTemplate.fileJson) {
        let files = JSON.parse(this.formTemplate.fileJson)
        this.filesData = files
        this.files = files
        this.editFile = null
      }
    },
    back() {
      if (this.active > 0) {
        this.active--
      }
    },
    close() {
      this.dialogVisible = false
    },
    initBoList() {
      this.boList = []
      request.get('${form}/bo/def/v1/getAll').then(response => {
        this.boList = response.data
      })
    },
    beforeClose() {
      this.dialogVisible = false
    },
    getBoDefData() {
      const {boDefIds} = this.formTemplate
      if (!boDefIds) return
      request.post('${form}/bo/def/v1/getBOTree', boDefIds).then(response => {
        this.boDefData = response.data
        this.varData = [{...response.data}]
        this.getData()
      })
    },
    getData() {
      if (this.boDefData && this.boDefData.children) {
        this.formTemplate.labelConfigs = this.boDefData.children
      }
    },
    getRuleState(rule) {
      if (!rule) {
        return 'defualt'
      }
      const roleJson = JSON.parse(rule)
      if (this.formTemplate.dataSourceForm == 'sql') {
        return !roleJson.filter || roleJson.filter == '[]'
          ? 'defualt'
          : 'success'
      } else {
        return !roleJson.condition || roleJson.condition.length == 0
          ? 'defualt'
          : 'success'
      }
    },
    conditionConfirm(result) {
      if (this.formTemplate.dataSourceForm == 'sql') {
        const resultJson = JSON.parse(result)
        result = this.transToConditions(result)
      }
      this.$set(this.editFile, 'rule', result)
      this.initFileJson(this.filesData)
    },
    transToConditions(result) {
      let resultJson = JSON.parse(result)
      if (resultJson.filter == '[]') {
        return null
      }
      resultJson.type = resultJson.filterType
      let filter = JSON.parse(resultJson.filter)
      let condition = []
      if (filter && filter.junction) {
        let junction = filter.junction
        if (filter.condition) {
          let conditions = filter.condition
          conditions.forEach(c => {
            if (c.junction) {
              if (c.condition) {
                let subCond = {branch: true, sub: []}
                let subConditions = c.condition
                subConditions.forEach(sub => {
                  let scond = this.getTransObj(sub, c.junction)
                  subCond.sub.push(scond)
                })
                condition.push(subCond)
              }
            } else {
              let cond = this.getTransObj(c, junction)
              condition.push(cond)
            }
          })
        }
      }
      resultJson.condition = condition
      return JSON.stringify(resultJson)
    },
    getTransObj(c, junction) {
      let cond = {
        compType: junction,
        flowvarKey: c.property,
        judgeCon1: c.operator,
        judgeVal1: c.value,
        ruleType: '1'
      }
      switch (c.dataType) {
        case 'number':
          cond.optType = '1'
          break
        case 'date':
          cond.optType = '3'
          break
        default:
          cond.optType = '2'
          break
      }
      cond.conDesc =
        c.chooseDesc +
        this.conditionReplaceChar +
        c.indexStr +
        this.conditionReplaceChar +
        c.style +
        this.conditionReplaceChar +
        c.dataType
      return cond
    },
    changeSQL(subSQL) {
      var word = subSQL.name
      request
        .get(
          `${window.context.portal}/base/tools/v1/getPinyin?chinese=${word}&type=0`
        )
        .then(response => {
          subSQL.alias = response.data.value
        })
    },
    editTemplateRule(row) {
      let json = row.rule
      this.editFile = row
      if (this.formTemplate.dataSourceForm == 'sql') {
        this.$refs.FormPrintTemplateSqlRuleDialog.showDialog(json)
      } else {
        this.$refs.FormPrintTemplateRuleCondition.showDialog(json)
      }
    },
    leaveTabVerify() {
      return new Promise((resolve, reject) => {
        this.$validator.validateAll('form').then(result => {
          if (result) {
            if (this.formTemplate.dataSourceForm == 'sql') {
              let mainSqlList = this.formTemplate.mainSqlList
              let url = '${form}/form/printTemplate/v1/getLabelData'
              let jsonData = {
                mainSqlList: mainSqlList,
                dsName: this.formTemplate.dataSource
              }
              request
                .post(url, jsonData)
                .then(response => {
                  if (this.componentType == 'add') {
                    this.formTemplate.mainSqlList =
                      response.data.value.mainSqlList
                  }
                  if (
                    this.formTemplate.mainSqlList &&
                    this.formTemplate.mainSqlList.length > 0
                  ) {
                    this.labelConfigs = this.formTemplate.mainSqlList[0].labelConfigs
                  }
                  resolve()
                })
                .catch(reason => reject())
            } else {
              if (!this.formTemplate.boDefIds) {
                this.active = 0
                this.$message.error('请选择数据来源')
                reject()
              }
              return true
            }
          } else {
            this.active = 0
            this.$message.error('表单未正确填写')
            reject()
          }
        })
      })
    },
    refresh() {
      this.$validator.validateAll('form').then(result => {
        if (result) {
          let mainSqlList = this.formTemplate.mainSqlList
          let url = '${form}/form/printTemplate/v1/getLabelData'
          let jsonData = {
            mainSqlList: mainSqlList,
            dsName: this.formTemplate.dataSource
          }
          request.post(url, jsonData).then(response => {
            this.formTemplate.mainSqlList = response.data.value.mainSqlList
          })
        }
      })
    },
    handleClick(data) {
      if (this.componentType == 'add') {
        this.getData()
      }
    },
    checkSql(diySql, dsName) {
      if(!this.formTemplate.dataSource) {
        this.$message('请选择数据源!')
        return
      }
      let data = {sql: diySql, dsName: dsName}
      if (!diySql) {
        this.$message('请填写自定义sql!')
        return
      }
      form.checkSql(data).then(
        response => {
          if (response.state) {
            this.$message({type: 'success', message: response.message})
          }
        },
        error => {
          this.$message.error('验证失败')
        }
      )
    },
    addSubSql(formTemplate) {
      if (!formTemplate.subSQList) {
        formTemplate.subSQList = []
      }
      formTemplate.subSQList.push({alias: '', name: ''})
    },
    uploadSuccess(response, file, fileList) {
      //获取附件类型
      let type = ''
      if (file.name && file.name.split('.')) {
        type = file.name.split('.')[1]
      } else {
        type = file.type
      }
      for (let i = 0; i < this.filesData.length; i++) {
        if (this.filesData[i].uid == file.uid) {
          this.filesData.splice(i, 1)
          break
        }
      }
      this.filesData.push({
        name: file.name,
        size: file.size,
        percentage: file.percentage,
        status: file.status,
        state: file.status,
        response: file.response,
        type: type,
        rule: null,
        uid: file.uid
      })
      this.$emit('onSuccess', response, file, fileList)
    },
    removeFile(file) {
      this.$confirm(`确定删除${file.name}?`)
        .then(() => {
          this.filesData.remove(file)
          this.$refs.fileUpload.remove(file)
          this.$emit('remove', file, this.files)
        })
        .catch(() => {})
    },
    download(row) {
      request.download('${portal}/system/file/v1/downloadFile?fileId=' + row.id)
    },
    beforeAvatarUpload(file) {
      var FileExt = file.name.replace(/.+\./, '')
      let index = this.fileAccept.lastIndexOf('.')
      let ext = this.fileAccept.slice(index + 1)
      if (ext != FileExt.toLowerCase()) {
        this.$message({
          type: 'warning',
          message: `请上传后缀名为${ext}的文档`
        })
        return false
      }
      if (file.size / 1024 / 1024 > this.fileSizeMax) {
        this.$message({
          type: 'warning',
          message:
            '附件【' + file.name + '】的大小超过' + this.fileSizeMax + 'M!'
        })
        return false
      }
      return true
    },
    onError(msg) {},
    //显示条件脚本对话框
    showConditionBuild() {
      this.$refs.flowConditionBuildDialog.showDialog()
    },
    //监听条件脚本确认事件
    conditionDialogConfirm(data) {
      const scriptStr = this.formTemplate.scriptStr
        ? this.formTemplate.scriptStr
        : ''
      this.$set(this.formTemplate, 'scriptStr', scriptStr + data)
    },
    varTreeOnConfirm(data) {
      const scriptStr = this.formTemplate.scriptStr
        ? this.formTemplate.scriptStr
        : ''
      this.$set(this.formTemplate, 'scriptStr', scriptStr + data.pathValue)
    },
    showScriptDialog() {
      this.$refs.printScriptDialog.showDialog({})
    },
    downloadWordTemplate() {
      window.location.href =
        window.context.manage + '/static/docx/printSetting.docx'
    },
    downloadExcelTemplate() {
      window.location.href =
        window.context.manage + '/static/excel/printSetting.xlsx'
    },
    submitTemplate() {
      let me_ = this
      //校验表单
      this.$validator.validateAll('form').then(result => {
        if (result) {
          if (
            this.formTemplate.dataSourceForm == 'bo' &&
            !this.formTemplate.boDefIds
          ) {
            this.$message.error('选择模型不能为空！')
            return
          }
          if (
            me_.formTemplate.dataSourceForm == 'sql' &&
            !me_.formTemplate.mainSqlList[0].mainInstId
          ) {
            me_.$message.error('请设置流程实例ID对应字段！')
            this.leaveTabVerify()
            this.active = 1
            return
          }
          if (!me_.formTemplate.fileJson) {
            this.$message.error('请上传套打模板！')
            this.active = 2
            return
          }
          // 保存数据
          let data = deepmerge({}, this.formTemplate, {clone: true})
          if (data.labelConfigs) {
            data.labelConfigs = JSON.stringify(data.labelConfigs)
          }
          if (data.mainSqlList) {
            data.mainSqlList = JSON.stringify(this.formTemplate.mainSqlList)
          }
          if(data.authModelType){
            delete data.authModelType
          }
          request
            .post('${form}/form/printTemplate/v1/saveFormPrintTemplate', data)
            .then(response => {
              if (response.data.state) {
                this.$message({
                  type: 'success',
                  message: response.data.message
                })
                this.dialogVisible = false
                this.$emit('onSerarch')
              }
            })
        } else {
          this.$message.error('表单未正确填写')
        }
      })
    }
  }
}
</script>

<style scoped>
.cv-edit__dialog /deep/ .el-dialog > .el-dialog__header {
  padding: 8px 20px;
  border-bottom: 1px solid #ddd;
}

.cv-edit__dialog /deep/ .el-dialog > .el-dialog__body {
  padding: 0 20px;
}

.table {
  width: 800px;
  min-height: 25px;
  line-height: 30px;
  text-align: center;
  border: 1px solid #ccc;
  border-collapse: collapse;
}

.table tr td,
.table tr th {
  border: 1px solid #ccc;
}

.el-input {
  width: 200px;
}
.scrollbar-fullheight {
  height: 100%;
}
.step-content {
  margin: 15px 35px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}
.clearfix:after {
  clear: both;
}
.box-card {
  margin: 15px 45px;
}
.print-card {
  width: 98%;
}
</style>
