<template>
  <section class="acAdd">
    <ai-detail list>
      <ai-title slot="title" :title="pageTitle">
        <template #rightBtn>
          <el-button type="primary" v-if="isEdit" @click="top.handleGetCode($route.query.id)">生成代码</el-button>
        </template>
      </ai-title>
      <template #content>
        <el-form ref="AcForm" :model="form" size="small" label-width="120px" :rules="rules">
          <el-tabs tab-position="left" @tab-click="handleSyncProps">
            <el-tab-pane label="基本信息" lazy>
              <ai-card title="基本信息">
                <template #content>
                  <el-row type="flex">
                    <div class="fill">
                      <el-form-item label="应用名称" prop="name">
                        <el-input v-model="form.name" clearable placeholder="请输入"/>
                      </el-form-item>
                      <el-form-item label="应用模块" prop="appName">
                        <el-input v-model="form.appName" clearable placeholder="请输入"/>
                      </el-form-item>
                    </div>
                    <div class="fill">
                      <el-form-item label="核心码" prop="rightCode">
                        <el-input v-model="form.rightCode" clearable placeholder="请输入"/>
                      </el-form-item>
                      <el-form-item label="详情方式" prop="detailType">
                        <ai-select v-model="form.detailType" :selectList="dict.getDict('detailType')"/>
                      </el-form-item>
                    </div>
                  </el-row>
                  <el-form-item label="按钮配置" prop="btns">
                    <el-checkbox-group v-model="form.btns">
                      <el-checkbox label="insertEnable">添加</el-checkbox>
                      <el-checkbox label="importEnable">导入</el-checkbox>
                      <el-checkbox label="exportEnalbe">导出</el-checkbox>
                      <el-checkbox label="editEnable">编辑</el-checkbox>
                      <el-checkbox label="deleteEnable">删除</el-checkbox>
                      <el-checkbox label="batchDelEnable">批量删除</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </template>
              </ai-card>
              <ai-card title="字段设置">
                <template #right>
                  <el-button type="text" @click="handleAddProps">批量添加</el-button>
                  <el-button type="text" @click="form.props.push({})">添加</el-button>
                </template>
                <template #content>
                  <ai-table :tableData="form.props" :isShowPagination="false" :colConfigs="colConfigs">
                    <el-table-column v-for="col in colConfigs" :key="col.slot" v-bind="col">
                      <template slot-scope="{row}">
                        <el-checkbox v-if="col.type=='checkBox'" v-model="row[col.slot]"/>
                        <span v-else-if="col.type=='chbShow'" v-text="row[col.slot]==true?'✔':''"/>
                        <el-input v-else size="small" v-model="row[col.slot]" placeholder="请输入" clearable/>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" slot="options" align="center">
                      <template slot-scope="{row,$index}">
                        <el-button type="text" @click="form.props.splice($index,1)">删除</el-button>
                      </template>
                    </el-table-column>
                  </ai-table>
                </template>
              </ai-card>
            </el-tab-pane>
            <el-tab-pane label="详情设计" lazy>
              <detail-layout v-bind="$props" :form="form" v-model="form.detailConfig"/>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="back">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </template>
    </ai-detail>
  </section>
</template>

<script>
import DetailLayout from "./detailLayout";

export default {
  name: "acAdd",
  components: {DetailLayout},
  props: {
    instance: Function,
    dict: Object,
    permissions: Function
  },
  inject: {
    top: {}
  },
  computed: {
    isEdit: v => !!v.$route.query.id,
    pageTitle: v => v.isEdit ? "编辑应用" : "新增应用"
  },
  data() {
    return {
      form: {props: [], btns: []},
      rules: {
        name: {required: true, message: "请输入应用名称"},
        appName: {required: true, message: "请输入应用模块"},
        btns: {required: true, message: '请输入按钮配置', trigger: 'change'}
      },
      colConfigs: [
        {slot: 'prop', label: "字段"},
        {slot: 'label', label: "名称"},
        {slot: 'dict', label: "字典"},
        {slot: 'isSearch', label: "搜索字段", align: 'center', type: 'checkBox'},
        {slot: 'isTable', label: "表格字段", align: 'center', type: 'checkBox'},
        {slot: 'isDetail', label: "详情字段", align: 'center', type: 'chbShow'},
      ]
    }
  },
  methods: {
    getDetail() {
      let {id} = this.$route.query
      id && this.instance.post("/node/aicode/detail", null, {
        params: {id}
      }).then(res => {
        if (res?.data) {
          this.form = res.data
          this.handleSyncProps()
        }
      })
    },
    back() {
      this.$router.push({})
    },
    submit() {
      this.$refs.AcForm.validate(v => {
        if (v) {
          this.instance.post("/node/aicode/addOrUpdate", this.form).then(res => {
            if (res?.code == 0) {
              this.$message.success("提交成功!")
              this.back()
            }
          })
        }
      })
    },
    handleSyncProps() {
      let detailPorps = this.form.detailConfig?.map(e => e.column)?.flat()?.map(e => e.prop)
      this.form.props = this.form.props.map(e => ({...e, isDetail: !!detailPorps?.includes(e.prop)}))
    },
    handleAddProps() {
      this.$prompt("请输入swagger示例JSON字符串", {
        type: 'warning',
        title: "批量添加字段",
        dangerouslyUseHTMLString: true,
        center: true,
      }).then(({value}) => {
        if (this.$checkJson(value)) {
          Object.keys(JSON.parse(value)).map(prop => {
            this.form.props.push({prop})
          })
        }
      }).catch(() => 0)
    },
    $checkJson(str) {
      if (typeof str == 'string') {
        try {
          let obj = JSON.parse(str);
          return !!(typeof obj == 'object' && obj);
        } catch (e) {
          return false;
        }
      }
      return false;
    },
  },
  created() {
    this.getDetail()
  }
}
</script>

<style lang="scss" scoped>
.acAdd {
  height: 100%;
}
</style>
