<template>
  <table>
    <colgroup>
      <col :class="$style.label" />
      <col :class="$style.input" />
    </colgroup>
    <tr v-show="false">
      <td>
        <sd-form-item name="appId" :input-props="{ defaultValue: appId }" />
        <sd-form-item name="appModuleId" :input-props="{ defaultValue: appModuleId }" />
      </td>
    </tr>
    <tr>
      <sd-form-item-td name="businessTypeName" />
    </tr>
    <tr>
      <td
        :class="{
          'ant-form-item-label': true,
          [$style.cell]: true,
          'sd-readonly': fields.businessTypeGroupId.readonly,
        }"
      >
        <label title="所属分组" class="ant-form-item-required"> 所属分组 </label>
      </td>
      <td
        :class="{
          'ant-form-item-control-wrapper': true,
          'sd-readonly': fields.businessTypeGroupId.readonly,
        }"
      >
        <a-form-model-item
          v-if="!fields.businessTypeGroupId.readonly"
          :label="null"
          :rules="[
            {
              required: true,
              message: '不能为空',
              trigger: ['change', 'blur'],
            },
          ]"
          prop="businessTypeGroupId"
        >
          <sd-tree-picker
            v-model="parentSel"
            single
            :load-tree-data="loadTreePickerData"
            @change="parentChange"
          />
        </a-form-model-item>
        <div v-else>
          {{ parentSel[0]?.name }}
        </div>
        <sd-form-item
          name="businessTypeGroupId"
          hidden
          :input-props="{ defaultValue: category.id }"
        />
      </td>
    </tr>
    <tr>
      <sd-form-item-td name="businessTypeDesc" />
    </tr>
    <tr>
      <sd-form-item-td name="belongLevel" />
    </tr>
    <tr>
      <sd-form-item-td name="flowField">
        <template v-slot>
          <sd-flow-picker
            v-model="model.flowField"
            single
            :app-id="formatAppId"
            @change="updateFlowFormModelRelationInfoId"
          />
        </template>
        <template v-slot:read>
          <span>{{ model.flowField && JSON.parse(model.flowField)[0].name }}</span>
        </template>
      </sd-form-item-td>
    </tr>
    <tr>
      <sd-form-item-td name="flowFormModelRelationInfoId">
        <template v-slot>
          <a-select v-if="formOpts.length === 0" />
          <a-select
            v-else
            v-model="model.flowFormModelRelationInfoId"
            :options="formOpts"
          ></a-select>
        </template>
        <template v-slot:read>
          <span>{{
            model.flowFormModelRelationInfoId &&
              formOpts.length &&
              formOpts.find((item) => item.id === model.flowFormModelRelationInfoId).label
          }}</span>
        </template>
      </sd-form-item-td>
    </tr>
    <tr>
      <sd-form-item-td name="manuscriptTitle">
        <a-button
          v-for="(item, index) in organizeLevel"
          :key="index"
          size="small"
          :class="$style.titleBtnstyle"
          @click="titleSetStyle(item.code)"
          >{{ item.name }}</a-button
        >
        <a-textarea id="manuscriptTitle" v-model="model.manuscriptTitle" auto-size />
      </sd-form-item-td>
    </tr>
    <tr>
      <sd-form-item-td name="flowTitleType">
        <a-radio-group v-model="model.flowTitleType">
          <a-radio value="0">
            由用户填写
          </a-radio>
          <a-radio value="1">
            按规则生成
            <a-tooltip
              title="使用该选项时，建议隐藏表单上的标题字段，否则标题数据会显示在表单上且为只读状态"
            >
              <a-icon type="exclamation-circle" :class="$style.icon" />
            </a-tooltip>
          </a-radio>
        </a-radio-group>
      </sd-form-item-td>
    </tr>
    <tr>
      <td> </td>
      <td colspan="3">
        <sd-form-item name="flowTitle" :to-backend-value="toName" :label="null">
          <div :class="$style.deptcontent">
            <a-textarea
              id="flowTitle"
              v-model="model.flowTitle"
              :auto-size="{ minRows: 2, maxRows: 4 }"
            />
            <a-button type="link" size="small" @click="select">设置 </a-button>
          </div>
        </sd-form-item>
      </td>
    </tr>
    <tr>
      <sd-form-item-td name="redHeadField">
        <template v-slot>
          <sd-select v-model="model.redHeadField" mode="multiple" :options="redheadOpts" />
        </template>
        <template v-slot:read>
          <span>{{
            model.redHeadField &&
              redheadOpts.length &&
              redheadOpts.find((item) => item.id === model.redHeadField).name
          }}</span>
        </template>
      </sd-form-item-td>
    </tr>
    <tr>
      <sd-form-item-td name="printTemplateField">
        <template v-slot>
          <sd-select v-model="model.printTemplateField" mode="multiple" :options="printOpts" />
        </template>
        <template v-slot:read>
          <span>{{
            model.printTemplateField &&
              printOpts.length &&
              printOpts.find((item) => item.id === model.printTemplateField).name
          }}</span>
        </template>
      </sd-form-item-td>
    </tr>
    <tr>
      <sd-form-item-td name="sortNumber" />
    </tr>
    <!-- 业务类型对应的表单权限不是统一配置时显示授权配置 -->
    <tbody v-show="allowAuth">
      <tr>
        <sd-form-item-td name="authRange">
          <a-radio-group v-model="model.authRange">
            <a-radio value="all">
              全部
            </a-radio>
            <a-radio value="range">
              按范围
            </a-radio>
          </a-radio-group>
        </sd-form-item-td>
      </tr>
      <tr v-if="model.authRange === 'range'">
        <sd-form-item-td name="rangeDeptMember">
          <div :class="$style.deptcontent">
            <sd-group-picker
              v-model="model.rangeDeptMember"
              v-bind="getFieldProps(fields.rangeDeptMember)"
            />
            <a-checkbox :checked="model.authSubIncluded === '1'" @change="setAuthSub">
              含下级</a-checkbox
            >
          </div>
        </sd-form-item-td>
      </tr>
      <tr>
        <sd-form-item-td
          name="rangeUserMember"
          :input-props="{ rootNode: getRootNode(fields.rangeUserMember) }"
        />
      </tr>
      <tr>
        <sd-form-item-td name="rangeRoleMember" />
      </tr>
    </tbody>
    <tr>
      <sd-form-item-td name="isShow" />
    </tr>
    <tr>
      <sd-form-item-td name="mobileStatus" />
    </tr>
    <tr>
      <sd-form-item-td name="status" />
    </tr>
    <a-modal
      :visible="visible"
      width="700px"
      title="标题设置"
      @cancel="visible = false"
      @ok="
        visible = false
        model.flowTitle = flowTitleTemp
      "
    >
      <a-textarea v-model="flowTitleTemp" placeholder="请从下方选择字段或文字" />
      <p />
      <a-list
        bordered
        :data-source="Object.keys(flowFieldsByCaption).filter((v) => v.includes(searchValue))"
        size="small"
        class="ant-transfer-list-content"
        :class="$style.fieldPicker"
      >
        <a-list-item
          slot="renderItem"
          slot-scope="item"
          class="ant-transfer-list-content-item"
          @click="flowTitleTemp = flowTitleTemp + `{${item}}`"
        >
          {{ item }}
        </a-list-item>
        <div slot="header">
          <a-input-search v-model="searchValue" placeholder="请输入搜索内容" />
        </div>
      </a-list>
    </a-modal>
  </table>
</template>

<script>
import PageService from '@/common/services/page-service'
import booleanUtil from '@/common/services/boolean-util'
import axios from '@/common/services/axios-instance'
import { message } from 'ant-design-vue'
import BusinesstypeService from './businesstype-service'
import components from './_import-components/sd-app-ywlx-form-import'

export default {
  name: 'SdAppYwlxForm',
  components,
  props: {
    model: {
      type: Object,
      required: true,
    },
    fields: {
      type: Object,
      required: true,
    },
    // 业务类型分组
    category: {
      type: Object,
      default: () => {},
    },
    appModuleInfo: {
      type: Object,
      default: () => {},
    },
    loadGroupTreeData: {
      type: Function,
      default: () => {},
    },
    // 公共应用（上级下放的）
    shareApp: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      booleanUtil,
      formOpts: [],
      organizeLevel: [], // 级别
      redheadOpts: [], // 红头的列表
      printOpts: [], // 打印模板配置选项
      parentSel: [],
      visible: false,
      flowFieldsByName: {},
      flowFieldsByCaption: {},
      flowTitleTemp: '',
      searchValue: '',
    }
  },
  computed: {
    appId() {
      return this.category?.props?.appId || ''
    },
    formatAppId() {
      return (this.shareApp ? 'N' : '') + this.appId
    },
    appModuleId() {
      return this.category?.props?.appModuleId || ''
    },
    allowAuth() {
      // 不使用可视化权限配置时，允许在业务类型中授权
      const id = this.appModuleId || this.model.appModuleId
      return this.appModuleInfo[id]?.usePermission !== '1'
    },
  },
  created() {
    // 分类中无模块id（根节点），需获取当前所属分组
    let p
    if (!this.appModuleId) {
      p = PageService.get(
        { id: this.model.businessTypeGroupId },
        'app/appbusinesstypegroup/weAppBusinessTypeGroup'
      ).then((res) => {
        const groupName = res.data?.pageFormData?.pageFieldInfos?.filter(
          (item) => item.name === 'name'
        )[0]?.value
        return { id: this.model.businessTypeGroupId, name: groupName }
      })
    } else {
      p = Promise.resolve({ id: this.category.id, name: this.category.text })
    }
    p.then((data) => {
      this.parentSel = [data]
    })
    // 非新建时，获取流程可用表单列表
    if (this.model.id) {
      this.getFlowFormModelRelationInfo()
    } else {
      // 新建时，获取默认流程
      this.getDefaultFlowDef(this.appModuleId).then((flowDef) => {
        if (flowDef) {
          this.model.flowField = [{ id: flowDef.id, name: flowDef.name }]
          this.updateFlowFormModelRelationInfoId(this.model.flowField)
        }
      })
    }
    this.getLevel()
    this.getRedHeadList()
    this.getPrintTemplateList()
    // 如果flowTitle有值，用汉字更新下
    if (this.model.flowTitle) {
      this.getFlowFields().then(() => {
        Object.keys(this.flowFieldsByName).forEach((key) => {
          this.model.flowTitle = this.model.flowTitle.replace(
            new RegExp(`{${key}}`, 'g'),
            `{${this.flowFieldsByName[key]}}`
          )
        })
      })
    }
  },
  methods: {
    loadTreePickerData(parentCatId) {
      return this.loadGroupTreeData(parentCatId, {
        appModuleId: this.appModuleId || this.model.appModuleId,
      })
    },
    getFieldProps(field) {
      let hierarchical = field.attr.hierarchical
      if (field.attr.hierarchical !== undefined) {
        hierarchical = booleanUtil.isTruthy(field.attr.hierarchical)
      }
      return {
        hierarchical,
        single: field.attr?.multiple === 'false',
        rootNode: this.belongedOrg
          ? [{ code: this.belongedOrg.id, ...this.belongedOrg }]
          : field.attr?.roots?.map((root) => {
              return { code: root.id, ...root }
            }),
      }
    },
    getRootNode(field) {
      // 以接口返回的roots为准
      return field.attr?.roots?.map((root) => {
        return { code: root.id, ...root }
      })
    },
    // 获取表单对应的流程
    getDefaultFlowDef(appModuleId) {
      return BusinesstypeService.getDefaultFlow({ appModuleId }).then((res) => res.data)
    },
    // 编辑时，获取流程可用表单列表
    getFlowFormModelRelationInfo() {
      const flowField = this.model.flowField
      const oFlowField = typeof flowField === 'string' ? JSON.parse(flowField) : flowField
      if (oFlowField?.[0]?.id) {
        BusinesstypeService.getFlowFormModelRelationInfoId(oFlowField[0].id).then((data) => {
          // 判断表单列表中是否包含了当前存储的表单
          const formId = this.model.flowFormModelRelationInfoId
          if (formId) {
            // 当前存储的表单在备选列表中不存在，则提示该表单已被删除
            if (!data.some((item) => item.id === formId)) {
              data.unshift({ label: '--此业务单已被删除，请重新选择--', value: formId })
            }
          }
          this.formOpts = data
        })
      }
    },
    // 选择完流程后，获取可用表单列表
    updateFlowFormModelRelationInfoId(item) {
      if (item?.[0]) {
        BusinesstypeService.getFlowFormModelRelationInfoId(item[0].id).then((data) => {
          data.forEach((item) => {
            if (item.defaultRelation) {
              this.model.flowFormModelRelationInfoId = item.value
            }
          })
          this.formOpts = data
        })
      } else {
        this.model.flowFormModelRelationInfoId = undefined
        this.formOpts = []
      }
    },
    getLevel() {
      BusinesstypeService.getOrganizeLevel().then((res) => {
        this.organizeLevel = res.datas
      })
    },
    titleSetStyle(item) {
      const manuscriptTitle = document.getElementById('manuscriptTitle')
      let strStyle = '{'
      strStyle = strStyle + item + '}'
      let value = this.model.manuscriptTitle
      if (
        value !== undefined &&
        (manuscriptTitle.selectionStart || manuscriptTitle.selectionStart === 0)
      ) {
        const startPos = manuscriptTitle.selectionStart
        const endPos = manuscriptTitle.selectionEnd
        value = value.substring(0, startPos) + strStyle + value.substring(endPos, value.length)
        this.$nextTick()
        manuscriptTitle.focus()
        manuscriptTitle.setSelectionRange(endPos + value.length, endPos + value.length)
      } else {
        value = strStyle
      }
      this.model.manuscriptTitle = value
    },
    setAuthSub(e) {
      this.model.authSubIncluded = e.target.checked ? '1' : '0'
    },
    getRedHeadList() {
      const params = {
        startPosition: 0,
        maxResults: -1,
        expressions: [
          {
            dataType: 'str',
            name: 'status',
            op: 'eq',
            stringValue: '1',
          },
          {
            dataType: 'exps',
            op: 'or',
            expressionsValue: [
              {
                dataType: 'str',
                name: 'appId',
                op: 'is_null',
              },
              {
                dataType: 'str',
                name: 'appId',
                op: 'eq',
                stringValue: this.appId,
              },
            ],
          },
        ],
        formId: 'oaRedhead',
        orderBy: 'appId asc,sortNum asc,creationTime desc',
        columns: 'id,redheadName,status',
      }

      PageService.getList(params).then((res) => {
        this.redheadOpts = res.data.data.map((val) => {
          return {
            id: val.id,
            name: val.redheadName,
          }
        })
      })
    },
    getPrintTemplateList() {
      const params = {
        startPosition: 0,
        maxResults: -1,
        expressions: [
          {
            dataType: 'str',
            name: 'status',
            op: 'eq',
            stringValue: '1',
          },
          {
            dataType: 'exps',
            op: 'or',
            expressionsValue: [
              {
                dataType: 'str',
                name: 'appId',
                op: 'is_null',
              },
              {
                dataType: 'str',
                name: 'appId',
                op: 'eq',
                stringValue: this.appId,
              },
            ],
          },
        ],
        formId: 'oaDocPrintTemplate',
        orderBy: 'appId asc,creationTime asc',
        columns: 'id,templateName,status,',
      }
      PageService.getList(params).then((res) => {
        this.printOpts = res.data.data.map((val) => {
          return {
            id: val.id,
            name: val.templateName,
          }
        })
      })
    },
    parentChange(data) {
      this.model.businessTypeGroupId = data[0]?.id || ''
    },
    getFlowFields() {
      if (!this.model.flowField || !this.model.flowFormModelRelationInfoId) {
        message.warn('请先选择使用的流程和表单')
        return Promise.resolve(false)
      }
      let flowField = this.model.flowField
      flowField = typeof flowField === 'string' ? JSON.parse(flowField) : flowField
      return axios
        .get(
          `api/framework/v1/businesstype-manage/findFieldsByRelationInfoId?flowId=${flowField[0].id}&flowFormModelRelationInfoId=${this.model.flowFormModelRelationInfoId}`
        )
        .then((res) => {
          res.data.forEach((item) => {
            Object.keys(item).forEach((key) => {
              this.flowFieldsByName[key] = item[key]
              this.flowFieldsByCaption[item[key]] = key
            })
          })
          return true
        })
    },
    toName(value) {
      if (value) {
        Object.keys(this.flowFieldsByCaption).forEach((key) => {
          value = value.replace(new RegExp(`{${key}}`, 'g'), `{${this.flowFieldsByCaption[key]}}`)
        })
      }
      return value
    },
    select() {
      this.getFlowFields().then((flag) => {
        if (!flag) return
        this.visible = true
        this.flowTitleTemp = this.model.flowTitle || ''
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
$titlemargin: 8px;
.title-btnstyle {
  margin-right: $titlemargin;
  background-color: $btn-disable-bg;
}
.deptcontent {
  display: flex;
  justify-content: space-between;
  :global(.ant-checkbox-wrapper) {
    width: 21%;
    text-align: right;
  }
}
.label {
  width: 20%;
}
.input {
  width: 80%;
}
.cell {
  display: table-cell;
}
</style>
