<template>
  <a-card>
    <sd-data-table
      ref="formTable"
      data-url="api/framework/v1/onlineform/list"
      :columns="columns"
      :actions="actions"
      :show-header="false"
      show-selection
      :filter-expressions="expressions"
      :search-fields="['tableTxt']"
      :process-req="processReq"
      :process-res="processRes"
      @rowClick="rowClick"
    >
      <div slot="tableTxt" slot-scope="text, record" :class="$style.formNameStyle">
        <a-list-item-meta :description="record.formDesc">
          <a slot="title">{{ text }}</a>
          <sd-icon
            slot="avatar"
            :type="record && record.iconObj && record.iconObj.name"
            :theme="record && record.iconObj && record.iconObj.theme"
            :class="$style.avatarclass"
          />
        </a-list-item-meta>
      </div>
      <div slot="formType" slot-scope="text">
        <a-tag v-if="text === 1">流程</a-tag>
        <a-tag v-else>无流程</a-tag>
      </div>
      <div slot="createBy" slot-scope="text">
        <div>创建人</div>
        <div>{{ text }}</div>
      </div>
      <div slot="createTime" slot-scope="text">
        <div>创建时间</div>
        <div>{{ text | sdDateFormat('YYYY-MM-DD HH:mm') }}</div>
      </div>
      <div slot="formStatus" slot-scope="text, record">
        <a-switch
          :loading="changeIds.includes(record.id)"
          :checked="text === 1"
          checked-children="启用"
          un-checked-children="停用"
          @change="changeFormStatus(record)"
        />
      </div>
      <div slot="operate" slot-scope="text, record" :class="$style.operatecol">
        <template v-if="!record.isDbSynch && isFlowForm(record)">
          <sd-form-guide
            :key="record.id"
            :record="record"
            @formDesign="formDesign"
            @flowDesign="flowDesignPage"
            @authCfg="authorityConfiguration"
            @dbSync="publish"
          />
        </template>
        <!-- 按钮最多显示3个，如需显示的按钮超过3个，则第3个开始显示在更多按钮中 -->
        <a-button
          v-for="btn in getCommonButtons(record)"
          :key="btn.type"
          type="link"
          size="small"
          @click="btnClick(btn, record)"
          >{{ btn.title }}</a-button
        >
        <a-dropdown v-if="getMoreButtons(record).length > 0" placement="bottomCenter">
          <a-button type="link" size="small">更多<a-icon type="down"/></a-button>
          <a-menu slot="overlay">
            <a-menu-item
              v-for="btn in getMoreButtons(record)"
              :key="btn.type"
              @click="btnClick(btn, record)"
            >
              {{ btn.title }}
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </div>
    </sd-data-table>
    <!-- 表单属性设置 -->
    <a-modal
      v-model="addFormVisible"
      :title="modalTitle"
      :class="$style.modalcontainer"
      width="700px"
      :confirm-loading="formConfirmLoading"
      @ok="onAddSubmit"
      @cancel="onFormCancel"
    >
      <a-form-model
        ref="addFormModal"
        :model="addForm"
        :rules="addFormRles"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item ref="name" label="表单名称" prop="name">
          <a-input v-model="addForm.name" />
        </a-form-model-item>
        <!-- 新建表单时显示模板选择 -->
        <a-form-model-item v-if="isNewForm()" label="使用模板">
          <SdFormTemplatePicker v-model="addForm.template" :templet-type="addForm.formType" />
        </a-form-model-item>
        <a-form-model-item label="表单图标" prop="icon">
          <sd-icon
            v-model="addForm.icon"
            :type="icon[0].name"
            :theme="icon[0].theme"
            :class="$style.iconclass"
          />
          <a-button @click="selectIcon">更改图标</a-button>
        </a-form-model-item>
        <a-form-model-item label="表单介绍" prop="desc">
          <a-input v-model="addForm.desc" type="textarea" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 导航配置 -->
    <a-modal
      v-model="navigationVisible"
      :title="'导航配置'"
      :class="$style.modalcontainer"
      width="700px"
      :confirm-loading="confirmLoading"
      @ok="navigationSubmit"
      @cancel="navigationCancel"
    >
      <a-form-model
        ref="navigationModal"
        :model="navigationData"
        :rules="navigationRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item ref="parentMenu" label="上级菜单" prop="parentMenu">
          <template v-if="!parentMenuReadOnly">
            <sd-value-picker
              v-model="navigationData.parentMenu"
              single
              option-value="code"
              option-label="label"
            >
              <template v-slot="scope">
                <sd-picker-source-tree :load-tree-data="loadTreeData" v-bind="scope" />
              </template>
            </sd-value-picker>
          </template>
          <template v-else>
            {{ navigationData.parentMenuName || '' }}
          </template>
        </a-form-model-item>
        <a-form-model-item ref="appMenuName" label="应用菜单" prop="appMenuName">
          <a-input v-model="navigationData.appMenuName" disabled />
        </a-form-model-item>
        <a-form-model-item ref="formMenuName" label="菜单名称" prop="formMenuName">
          <a-input v-model="navigationData.formMenuName" />
        </a-form-model-item>
        <a-form-model-item ref="listFormUrl" prop="listFormUrl">
          <template slot="label">
            <a-checkbox
              :checked="navigationData.isListCreated === 1"
              :disabled="!navigationData.listFormUrl"
              @change="
                () => {
                  navigationData.isListCreated = navigationData.isListCreated === 1 ? 0 : 1
                }
              "
            />
            列表地址
          </template>
          <a-input v-model="navigationData.listFormUrl" disabled />
        </a-form-model-item>
        <a-form-model-item v-if="isFlowForm(currentForm)" ref="createFormUrl" prop="createFormUrl">
          <template slot="label">
            <a-checkbox
              :checked="navigationData.isCreateCreated === 1"
              :disabled="!navigationData.createFormUrl"
              @change="
                () => {
                  navigationData.isCreateCreated = navigationData.isCreateCreated === 1 ? 0 : 1
                }
              "
            />
            新建地址
          </template>
          <a-input v-model="navigationData.createFormUrl" disabled />
        </a-form-model-item>
        <a-form-model-item
          v-if="navigationData.statisFormUrl"
          ref="statisFormUrl"
          prop="statisFormUrl"
        >
          <template slot="label">
            <a-checkbox
              :checked="navigationData.isStatisCreated === 1"
              @change="
                () => {
                  navigationData.isStatisCreated = navigationData.isStatisCreated === 1 ? 0 : 1
                }
              "
            />
            统计地址
          </template>
          <a-input v-model="navigationData.statisFormUrl" disabled />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 权限配置 -->
    <sd-detail-modal
      ref="appDetail"
      :record-id="appDetailId"
      page-id="base/businesstype/oaBaseBusinessType"
      :modal-props="{ width: 800 }"
      @actionBtnClick="groupDetailSaved"
    >
      <template v-slot="scope">
        <SdYwlxForm
          v-bind="scope"
          :category-id="categoryId"
          :category-name="categoryName"
          :default-flow="flowField"
          :default-status="status"
        />
      </template>
    </sd-detail-modal>
    <sd-business-list-config ref="listConfig" />
    <sd-form-perm-config ref="permConfig" />
    <sd-business-statis-config ref="statisConfig" />
    <!-- 导入表单 -->
    <a-modal
      title="导入表单"
      :visible="visible"
      :width="650"
      destroy-on-close
      :mask-closable="false"
      :confirm-loading="importConfirmLoading"
      @ok="importfromfile"
      @cancel="visible = false"
    >
      <sd-form ref="importForm" :init-values="formData">
        <template v-slot="{ model, fields }">
          <sd-form-item name="attachment" />
          <sd-form-item name="type">
            <a-radio-group v-model="model.type">
              <a-radio
                v-for="item in fields.type.attr.selectListItem"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
                <a-tooltip v-if="['1', '2'].includes(item.value)">
                  <template v-slot:title>
                    {{
                      item.value === '1'
                        ? '覆盖重复的表单及表单的权限配置、列表配置、导航配置和流程设计'
                        : '检查表单是否有重复，只要有一个重复则全部停止导入'
                    }}
                  </template>
                  <a-icon type="question-circle-o" />
                </a-tooltip>
              </a-radio>
            </a-radio-group>
          </sd-form-item>
          <sd-form-item name="appId" hidden />
        </template>
      </sd-form>
    </a-modal>
  </a-card>
</template>

<script>
import { Message, Modal } from 'ant-design-vue'
import pickValues from '@/common/services/pick-values'
import sdIconPicker from '@/common/components/sd-icon-picker.vue'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import axios from '@/common/services/axios-instance'
import loginService from '@/login/login-service'
import PageService from '@/common/services/page-service'
import FormService from '@/form-designer/form-service'
import download from '@/common/services/download'
import moment from 'moment'
import SdFormTemplatePicker from '@/form-designer/form-template/sd-form-template-picker.vue'
import SdYwlxForm from '@/business-type/sd-ywlx-form.vue'
import { sdLocalStorage } from '@/common/services/storage-service'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import components from './_import-components/sd-form-center-import'
import ApplicationService from './application-service'
const saveParams = {
  head: {
    id: '',
    tableName: '',
    tableType: 1,
    tableTxt: '',
    formType: 1,
    formCategory: 'default',
    formTemplate: 'formTemplate',
    formDesc: '',
    iconCode: '',
    isCheckbox: false,
    isPage: true,
    isTree: false,
    relationType: 1,
    tabOrderNum: 1,
    scroll: false,
    attrFD: {},
  },
  fields: [],
}
export default {
  name: 'SdFormCenter',
  components: {
    ...components,
    SdFormTemplatePicker,
    SdYwlxForm,
  },
  metaInfo() {
    return {
      title: this.$route.query.appName,
    }
  },
  data() {
    return {
      appId: '',
      parentMenuReadOnly: false,
      expressions: [
        {
          dataType: 'str',
          name: 'formCategory',
          op: 'eq',
          stringValue: this.$route.query.appId,
        },
      ],
      columns: [
        {
          title: '名称',
          dataIndex: 'tableTxt',
          sdClickable: true,
          scopedSlots: { customRender: 'tableTxt' },
        },
        {
          title: '表单类型',
          dataIndex: 'formType',
          scopedSlots: { customRender: 'formType' },
          width: '80px',
        },
        {
          title: '创建者',
          dataIndex: 'createBy',
          scopedSlots: { customRender: 'createBy' },
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          sdRender: TableColumnTypes.dateTime,
          defaultSortOrder: 'descend',
          sorter: true,
          sortDirections: ['ascend', 'descend'],
          scopedSlots: { customRender: 'createTime' },
        },
        {
          title: '启用',
          dataIndex: 'formStatus',
          scopedSlots: { customRender: 'formStatus' },
          width: '100px',
        },
        {
          title: '操作',
          dataIndex: 'id',
          scopedSlots: { customRender: 'operate' },
          width: '260px',
        },
      ],
      actions: [
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.batch,
          permission: null,
          callback: this.delForm,
        },
        {
          label: '初始化',
          id: 'reset',
          type: TableActionTypes.batch,
          permission: null,
          callback: this.resetForm,
        },
        {
          label: '导出',
          id: 'export',
          type: TableActionTypes.batch,
          permission: null,
          callback: this.exportForm,
        },
        {
          label: '导入',
          id: 'importForm',
          permission: null,
          callback: this.importForm,
        },
      ],
      status: '0', // 表单新建业务类型维护时默认状态停用，发布表单时启用
      flowField: null,
      appDetailId: null,
      currentForm: null,
      addFormVisible: false,
      navigationVisible: false,
      modalTitle: '新建表单',
      addForm: {
        name: '',
        desc: '',
        formType: 1,
        icon: [{ id: 'sd-audio-circle/fill', name: 'sd-audio-circle', theme: 'fill' }],
      },
      navigationData: {},
      icon: [{ id: 'sd-audio-circle/fill', name: 'sd-audio-circle', theme: 'fill' }],
      addFormRles: {
        name: [
          { required: true, message: '请输入表单名称', trigger: 'change' },
          { max: 100, message: '不能超过100个字符', trigger: 'change' },
        ],
        icon: [{ required: true, message: '请选择表单图标', trigger: 'change' }],
        desc: [{ max: 500, message: '不能超过500个字符', trigger: 'change' }],
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      navigationRules: {
        parentMenu: [{ required: true, message: '请选择上级菜单', trigger: 'change' }],
        formMenuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        listFormUrl: [{ message: '请输入列表地址', trigger: 'blur' }],
        createFormUrl: [{ message: '请输入新建地址', trigger: 'blur' }],
      },
      formId: '', // 表单ID
      categoryId: this.$route.query.categoryId, // 业务类型ID
      categoryName: JSON.parse(this.$route.query.categoryName)[0].name, // 业务类型名称
      routeChange: false,
      confirmLoading: false,
      changeIds: [],
      formConfirmLoading: false,
      syncDbing: false,
      copying: false,
      visible: false,
      formData: [],
      importConfirmLoading: false,
    }
  },
  created() {
    this.initd()
  },
  methods: {
    initd() {
      this.appId = this.$route.query.appId
      // 默认不显示“新建流程表单”按钮
      this.actions = this.actions.filter((item) => item.id !== 'new')
      // 获取当前应用状态
      PageService.get({ id: this.appId }, 'online/app/oaOnlineApp').then((res) => {
        const state = res.data?.pageFormData?.pageFieldInfos?.filter(
          (item) => item.name === 'isPublished'
        )[0]?.value
        // 非暂停状态，可显示按钮“新建流程表单”
        if (state !== 2) {
          this.actions.push({
            label: '新建流程表单',
            id: 'new',
            type: TableActionTypes.primary,
            permission: null,
            callback: this.addFormFunc,
            children: [
              {
                label: '新建无流程表单',
                id: 'newNoFlow',
                permission: null,
                callback: this.addNoFlowFormFunc,
              },
            ],
          })
        }
      })
    },
    getImportFormData() {
      return [
        {
          name: 'appId',
          dataType: 'String',
          caption: '所属应用',
          readonly: false,
          required: false,
          value: this.appId,
        },
        {
          name: 'type',
          dataType: 'selectlist',
          caption: '表单重复时',
          readonly: false,
          required: false,
          attr: {
            defaultValue: '0',
            multiple: 'false',
            selectListItem: [
              {
                label: '跳过',
                value: '0',
              },
              {
                label: '覆盖',
                value: '1',
              },
              {
                label: '停止导入',
                value: '2',
              },
            ],
          },
        },
        {
          name: 'attachment',
          dataType: 'attachment',
          caption: '附件',
          readonly: false,
          required: true,
          value: '{"value":"' + this.filegroupid() + '"}',
          attr: {
            allowType: '.gz',
            maxLength: 1,
            uploadable: true,
          },
        },
      ]
    },
    // 获取表单对应的流程设计
    getFlowDef(formId) {
      return ApplicationService.businessValue({
        appId: this.appId,
        formId,
      }).then((res) => {
        if (res.data) {
          return JSON.parse(res.data.flow)
        }
      })
    },
    // 获取表单对应的权限配置
    getAuthorityConfig(formId) {
      return ApplicationService.queryBusinessid(formId).then((res) => {
        if (res) {
          return Number(res)
        }
      })
    },
    // 检测表单对应的导航配置
    getNavigationConfig(formId) {
      return ApplicationService.getMenuInfo({
        appId: this.appId,
        formId,
      }).then((res) => {
        return res.data
      })
    },
    publish(record) {
      if (!this.syncDbing) {
        Modal.confirm({
          title: '您确定将表单设计同步到数据库吗？',
          content: '同步后只允许对表单字段属性进行修改, 无法新增、删除字段',
          onOk: () => {
            this.syncDbing = true
            const key = 'syncdb'
            const duration = 1
            Message.loading({ content: '同步中，请稍候...', key, duration: 0 })
            axios
              .post(`api/framework/v1/onlineform/doDbSynch/${record.id}/normal`)
              .then(() => {
                Message.success({ content: '同步成功！', key, duration })
                this.$refs.formTable.refresh(true)
              })
              .catch(() => {
                Message.error({ content: '同步失败', key, duration })
              })
              .finally(() => {
                this.syncDbing = false
              })
          },
        })
      }
    },
    flowDesignPage() {
      loginService.updateAccessToken().then((accessToken) => {
        const sysManageUrl = JSON.parse(sdLocalStorage.getItem('commonConfig') || '{}').weSysManage
          ?.sysManageUrl
        const url = `api/ssologin?destUrl=${sysManageUrl}/admin/flowNew/designer.jsp&token=${accessToken.replace(
          'Bearer ',
          ''
        )}`
        const newWindow = window.open(url, '_blank')
        newWindow.opener = null
      })
    },
    rowClick(record) {
      this.editForm(record)
    },
    processReq(req) {
      if (this.routeChange) {
        this.routeChange = false
        req.data.expressions = [
          {
            dataType: 'str',
            name: 'formCategory',
            op: 'eq',
            stringValue: this.appId,
          },
        ]
      }
      if (req.data.expressions.length > 0) {
        var that = this
        req.data.expressions.map(function(exp, index) {
          if (exp.expressionsValue && exp.expressionsValue[0].name === 'tableTxt') {
            req.data.expressions[index] = exp.expressionsValue[0]
          }
          if (exp.name === 'formCategory') {
            exp.stringValue = that.$route.query.appId
          }
        })
      }
      return req
    },
    processRes(res) {
      if (res.data.length > 0) {
        res.data.map(function(data) {
          data.iconObj = JSON.parse(data.iconCode)
        })
      }
      return res
    },
    isNewForm() {
      return saveParams.head.id === ''
    },
    // 新建流程表单
    addFormFunc(isNoFlow = false) {
      this.modalTitle = isNoFlow ? '新建无流程表单' : '新建流程表单'
      this.addForm = {
        name: '',
        desc: '',
        formType: isNoFlow ? 0 : 1,
        icon: [{ id: 'sd-audio-circle/fill', name: 'sd-audio-circle', theme: 'fill' }],
      }
      this.icon = this.addForm.icon
      this.addFormVisible = true
      saveParams.head.id = ''
      saveParams.head.tableName = ''
      saveParams.head.formCategory = this.appId
      saveParams.head.attrFD = {}
      saveParams.fields = []
    },
    addNoFlowFormFunc() {
      this.addFormFunc(true)
    },
    // 表单设计
    formDesign(item) {
      crossWindowWatcher
        .waitForChanged(`/sd-form-designer/${item.id}?type=${item.formType}`)
        .then(() => {
          this.$refs.formTable.refresh(true)
        })
    },
    // 列表设计
    listDesign(item) {},
    // 权限配置
    authorityConfiguration(item) {
      this.formId = item.id
      // 获取业务类型id
      this.getAuthorityConfig(item.id)
        .then((res) => {
          if (res) {
            this.appDetailId = Number(res)
          } else {
            this.appDetailId = null
            // 新建时获取表单业务类型的默认表单流程
            return this.getFlowDef(item.id)
              .then((res) => {
                if (res) {
                  this.flowField = res
                }
              })
              .catch((e) => {
                Message.error({ content: '获取默认流程失败' })
              })
          }
        })
        .then(() => {
          this.$refs.appDetail.show()
        })
        .catch((e) => {
          Message.error({ content: '获取业务类型表单失败' })
        })
    },
    // 保存业务类型Id
    groupDetailSaved(evt, btn) {
      if (btn.buttonId === 'save') {
        evt.preventDefault()
        this.$refs.appDetail.save().then((res) => {
          const params = {
            formId: this.formId,
            businessTypeId: res.data.pageFormData.beanId,
          }
          ApplicationService.saveBusinessid(params)
            .then((res) => {
              this.$refs.appDetail.hide()
              Message.success('保存成功')
            })
            .catch((e) => {
              Message.error({ content: '保存失败' })
            })
        })
      }
    },
    // 导航配置
    navigationConfiguration(item) {
      this.currentForm = item
      this.navigationVisible = true
      this.getNavigationConfig(item.id)
        .then((data) => {
          this.navigationData = data
          // 第一次配置导航时，菜单地址默认选中
          if (!this.navigationData.formMenuName) {
            // 列表地址不为空时，默认选中
            if (this.navigationData.listFormUrl) {
              this.navigationData.isListCreated = 1
            }
            // 统计地址不为空时，默认选中
            if (this.navigationData.statisFormUrl) {
              this.navigationData.isStatisCreated = 1
            }
            // 流程表单 且 新建地址不为空时，默认选中
            if (this.isFlowForm(item) && this.navigationData.createFormUrl) {
              this.navigationData.isCreateCreated = 1
            }
          }
          if (data.parentMenuId && data.parentMenuName) {
            this.navigationData.parentMenu = [
              { code: data.parentMenuId, label: data.parentMenuName },
            ]
            this.parentMenuReadOnly = true
          }
          this.navigationData.appMenuName = data.appMenuName || this.$route.query.appName
          // 非流程表单，且列表地址为空，则赋上默认值
          if (!this.isFlowForm(item) && !this.navigationData.listFormUrl) {
            this.navigationData.listFormUrl = `/sd-frame/sd-business-list?headId=${item.id}`
          }
        })
        .catch((e) => {
          Message.error({ content: '获取菜单信息失败' })
        })
    },
    editForm(item) {
      ApplicationService.getFormDetail(item.id)
        .then((res) => {
          this.modalTitle = res.data.head.formType === 1 ? '修改流程表单' : '修改无流程表单'
          this.addFormVisible = true
          this.addForm = {
            name: res.data.head.tableTxt,
            desc: res.data.head.formDesc,
            formType: res.data.head.formType,
            icon: [JSON.parse(res.data.head.iconCode)],
          }
          this.icon = this.addForm.icon
          saveParams.head = res.data.head
          saveParams.fields = res.data.fields
        })
        .catch((e) => {
          Message.error({ content: '表单详情查询失败' })
        })
    },
    resetForm(ids, records) {
      const allowReset = records.findIndex((item) => item.formStatus === 1) === -1
      if (!allowReset) {
        Message.warning(`不能初始化“启用”状态的表单`)
        return
      }
      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定初始化选择的表单吗？',
          content: '初始化后，表单对应的所有业务数据均会被删除，无法恢复！您确认要执行此操作吗？',
          okType: 'danger',
          onOk: () => {
            const key = 'resetform'
            const duration = 1
            Message.loading({ content: '正在初始化，请稍候...', key, duration: 0 })
            ApplicationService.resetForm(ids)
              .then((res) => {
                if (!res.data?.success) {
                  Message.error({ content: res.data?.message || '初始化表单出错', key, duration })
                } else {
                  Message.success({ content: '初始化成功！', key, duration })
                }
                this.$refs.formTable.refresh(true)
                this.$refs.formTable.clearSelection()
              })
              .catch((e) => {
                Message.error({ content: '初始化表单失败', key, duration })
              })
              .finally(() => {
                resolve()
              })
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
    // 复制表单
    copyForm(item) {
      if (!this.copying) {
        const params = {
          headId: item.id,
          newFormName: `${item.tableTxt}-副本`,
        }
        this.copying = true
        const key = 'copyform'
        const duration = 1
        Message.loading({ content: '复制中，请稍候...', key, duration: 0 })
        ApplicationService.copyForm(params)
          .then((res) => {
            Message.success({ content: '复制成功！', key, duration })
            this.$refs.formTable.refresh(true)
          })
          .catch((e) => {
            Message.error({ content: '复制表单失败', key, duration })
          })
          .finally(() => {
            this.copying = false
          })
      }
    },
    delForm(ids, records) {
      // 停用的表单才能删除
      const allowDel = records.findIndex((item) => item.formStatus === 1) === -1
      if (!allowDel) {
        Message.warning('不能删除“启用”状态的表单')
        return
      }
      return new Promise((resolve) => {
        var params = {
          ids: ids.join(','),
          flag: '1',
        }
        Modal.confirm({
          title: '您确定删除选择的内容吗？',
          content: '删除数据后，对应的业务数据无法恢复，请确认是否删除？',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            ApplicationService.delForm(params)
              .then((res) => {
                if (!res.data?.success) {
                  if (res.data?.message) {
                    Modal.info({
                      content: res.data.message
                        .split('\r\n')
                        .map((item) => (item ? <div class={this.$style.deltips}>{item}</div> : '')),
                      class: this.$style.deltipsmodal,
                    })
                  }
                }
                this.$refs.formTable.refresh(true)
                this.$refs.formTable.clearSelection()
                resolve()
              })
              .catch((e) => {
                Message.error({ content: '删除表单失败' })
                resolve()
              })
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },
    exportForm(ids, records) {
      const fileName =
        records.map((item) => item.tableTxt).join('、') + '-' + moment().format('YYYYMMDD')
      return download(`api/xcoa-mobile/v1/onlineform/export?formIds=${ids}`, `${fileName}.gz`, true)
    },
    importForm() {
      this.formData = this.getImportFormData()
      this.visible = true
    },
    filegroupid() {
      return 'form_' + new Date().getTime() + '_' + (Math.floor(Math.random() * 100) + 1)
    },
    importfromfile() {
      this.$refs.importForm.validateFields().then((flag) => {
        if (flag) {
          const data = this.$refs.importForm.getFieldsValue()
          let p = Promise.resolve(true)
          // 选择覆盖时，进行二次确认
          if (data.type === '1') {
            p = new Promise((resolve) => {
              Modal.confirm({
                title: '您确定表单重复时覆盖吗？',
                content:
                  '覆盖表单后，表单的权限配置、列表配置、导航配置和流程设计也会覆盖，请确认是否覆盖？',
                okText: '确认',
                okType: 'danger',
                onOk: () => {
                  resolve(true)
                },
                onCancel: () => {
                  resolve(false)
                },
              })
            })
          }
          p.then((isContinue) => {
            if (isContinue) {
              data.fileId = data.attachment?.[0]?.code
              delete data.attachment
              this.importFormSubmit(data)
            }
          })
        }
      })
    },
    importFormSubmit(data) {
      this.importConfirmLoading = true
      ApplicationService.importForm(data)
        .then((res) => {
          const msg = res.data?.message
          switch (res.data?.code) {
            case 0:
              Modal.confirm({
                title: msg,
                content: '导航菜单已更新，是否刷新页面？',
                okText: '刷新',
                cancelText: '不刷新',
                onOk: () => {
                  window.location.reload()
                },
              })
              this.$refs.formTable.refresh(true)
              this.visible = false
              break
            case 2:
              Message.warning(msg)
              this.visible = false
              break
            case 3:
              Modal.confirm({
                title: '导入完成！',
                content: msg
                  .split('\r\n')
                  .map((item) => (item ? <div>{item}</div> : ''))
                  .concat([<p>导航菜单已更新，是否刷新页面？</p>]),
                okText: '刷新',
                cancelText: '不刷新',
                onOk: () => {
                  window.location.reload()
                },
              })
              this.$refs.formTable.refresh(true)
              this.visible = false
              break
            default:
              Message.error(msg || '导入出错：原因未知')
              break
          }
        })
        .finally(() => {
          this.importConfirmLoading = false
        })
    },
    changeFormStatus(record) {
      let formStatus = 0
      let operate = ''
      if (record.formStatus !== 1) {
        formStatus = 1
        operate = '启用'
      } else {
        formStatus = 2
        operate = '停用'
      }
      Modal.confirm({
        title: `您确定${operate}该表单吗？`,
        content: '此操作会清空所有用户导航缓存，导致用户导航会重新生成一次',
        okText: operate,
        okType: formStatus === 2 ? 'danger' : '',
        onOk: () => {
          const headId = record.id
          this.changeIds.push(headId)
          ApplicationService.changeFormStatus({ headId, formStatus })
            .then((res) => {
              if (res && res.data && res.data.success) {
                Modal.confirm({
                  title: `${operate}表单成功`,
                  content: '导航菜单已更新，是否刷新页面？',
                  okText: '刷新',
                  cancelText: '不刷新',
                  onOk: () => {
                    // 发布/暂停 完成后刷新当前页面（导航菜单会更新）
                    window.location.reload()
                  },
                })
                this.$refs.formTable.refresh(true)
              } else {
                Message.error({
                  content: res.data.message ? res.data.message : `${operate}表单失败`,
                })
              }
            })
            .catch(() => {
              Message.error({ content: `${operate}表单失败` })
            })
            .finally(() => {
              this.changeIds = this.changeIds.filter((item) => item !== headId)
            })
        },
      })
    },
    onAddSubmit() {
      this.$refs.addFormModal.validate((valid) => {
        if (valid) {
          this.formConfirmLoading = true
          var iconValue = {
            id: this.icon[0].id,
            name: this.icon[0].name,
            theme: this.icon[0].theme,
          }
          saveParams.head.tableTxt = this.addForm.name
          saveParams.head.iconCode = JSON.stringify(iconValue)
          saveParams.head.formDesc = this.addForm.desc || ''
          saveParams.head.formType = this.addForm.formType
          if (saveParams.head.id) {
            ApplicationService.modifyForm(saveParams)
              .then((res) => {
                this.addFormVisible = false
                this.$refs.formTable.refresh(true)
              })
              .catch((e) => {
                Message.error({ content: '表单更新失败' })
              })
              .finally(() => {
                this.formConfirmLoading = false
              })
          } else {
            let p = Promise.resolve(true)
            // 选择了表单模板
            if (this.addForm.template?.[0]) {
              p = FormService.getFormTemplateData({ id: this.addForm.template[0].id }).then(
                (data) => {
                  saveParams.head.attrFD = data.attrFd
                  saveParams.fields = data.fields
                }
              )
            }
            p.then(() => {
              ApplicationService.createForm(saveParams)
                .then((res) => {
                  this.addFormVisible = false
                  this.$refs.formTable.refresh(true)
                })
                .catch((e) => {
                  Message.error({ content: '表单创建失败' })
                })
                .finally(() => {
                  this.formConfirmLoading = false
                })
            }).catch(() => {
              Message.error({ content: '获取表单模板信息失败' })
              this.formConfirmLoading = false
            })
          }
        } else {
          return false
        }
      })
    },
    onFormCancel() {
      this.$refs.addFormModal.resetFields()
    },
    navigationSubmit() {
      this.$refs.navigationModal.validate((valid) => {
        if (valid) {
          // 菜单地址必须勾选一个
          let hasMenu = false
          if (this.isFlowForm(this.currentForm)) {
            // 流程表单：新建、列表、统计
            hasMenu =
              this.navigationData.isCreateCreated === 1 ||
              this.navigationData.isListCreated === 1 ||
              this.navigationData.isStatisCreated === 1
          } else {
            // 无流程表单：列表、统计
            hasMenu =
              this.navigationData.isListCreated === 1 || this.navigationData.isStatisCreated === 1
          }
          if (hasMenu) {
            this.navigationData.parentMenuId = this.navigationData.parentMenu[0].code
            this.navigationData.parentMenuName = this.navigationData.parentMenu[0].label
            this.confirmLoading = true
            ApplicationService.saveMenuInfo(this.navigationData)
              .then((res) => {
                this.navigationVisible = false
                this.confirmLoading = false
                // 导航配置完成后刷新当前页面
                window.location.reload()
              })
              .catch((e) => {
                Message.error({ content: '导航配置失败' })
              })
              .finally(() => {
                this.confirmLoading = false
              })
          } else {
            Message.warn('请至少勾选一个导航菜单地址')
          }
        } else {
          return false
        }
      })
    },
    navigationCancel() {
      this.$refs.navigationModal.resetFields()
    },
    selectIcon() {
      pickValues(sdIconPicker, {
        value: this.icon,
      })
        .then((icons) => {
          this.icon = icons || this.icon
        })
        .then((icons) => {
          this.addForm.icon = icons || this.form.icon
        })
    },
    loadTreeData(parentCatId) {
      var params = { parentId: parentCatId || -1 }
      return ApplicationService.getMenuList(params).then((res) => {
        return res.data.map(function(item) {
          return {
            code: item.id,
            label: item.text,
            checkable: true, // 是否有选择框
            isLeaf: item.leaf, // 是否跟节点
          }
        })
      })
    },
    isFlowForm(item) {
      return item?.formType === 1
    },
    getButtons(item) {
      const btns = []
      if (item) {
        // 表单设计
        btns.push({ type: 'formDesign', title: '表单设计' })
        // 流程设计、权限配置
        if (this.isFlowForm(item)) {
          btns.push({ type: 'flowDesign', title: '流程设计' })
          btns.push({ type: 'authConfig', title: '权限配置' })
        } else {
          btns.push({ type: 'permConfig', title: '权限配置' })
        }
        btns.push({ type: 'listConfig', title: '列表配置' })
        // 统计配置
        btns.push({ type: 'statisConfig', title: '统计配置' })

        // 导航配置
        btns.push({ type: 'naviConfig', title: '导航配置' })
        // 同步到数据库
        if (!item.isDbSynch) {
          btns.push({ type: 'syncDb', title: '同步到数据库' })
        }
        btns.push({ type: 'copy', title: '复制' })
      }
      return btns
    },
    getCommonButtons(item) {
      const buttons = this.getButtons(item)
      if (buttons.length > 3) {
        return buttons.splice(0, 2)
      }
      return buttons
    },
    getMoreButtons(item) {
      const buttons = this.getButtons(item)
      if (buttons.length > 3) {
        buttons.splice(0, 2)
        return buttons
      }
      return []
    },
    btnClick(btn, item) {
      switch (btn.type) {
        case 'formDesign':
          this.formDesign(item)
          break
        case 'flowDesign':
          this.flowDesignPage()
          break
        case 'authConfig':
          this.authorityConfiguration(item)
          break
        case 'naviConfig':
          this.navigationConfiguration(item)
          break
        case 'syncDb':
          this.publish(item)
          break
        case 'copy':
          this.copyForm(item)
          break
        case 'listConfig':
          this.$refs.listConfig.show(item)
          break
        case 'statisConfig':
          this.$refs.statisConfig.show(item.id)
          break
        case 'permConfig':
          this.$refs.permConfig.show(item.id)
          break
        default:
          break
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.form-search-container {
  display: inline-block;
  width: 100%;
  padding-bottom: 15px;
  border-bottom: 1px solid #e8e8e8;
  .search-class {
    float: right;
    width: 240px;
  }
  .add-form-btn {
    float: right;
    margin-left: 10px;
  }
}
.creator-container {
  width: 150px;
  text-align: center;
}
.iconclass {
  margin-right: 8px;
  font-size: $font-size-base * 2;
  vertical-align: middle;
}
.form-menus {
  float: left;
  width: 165px;
  text-align: center;
  div {
    padding: 5px 0;
  }
  .menu-form-design {
    background-color: $primary-2;
  }
  .menu-process-design {
    cursor: pointer;
  }
}
.form-name-style {
  :global(.ant-list-item-meta-title > a) {
    color: $primary-color;
  }
}
.avatarclass {
  font-size: $font-size-base * 3;
}
.operatecol {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  :global(.ant-btn-sm) {
    padding: 0 3px;
  }
  :global(.ant-btn > span + .anticon) {
    margin-left: 4px;
  }
}
.deltipsmodal {
  :global(.anticon) {
    display: none;
  }
  .deltips {
    text-indent: 2em;
  }
}
</style>
