<template>
  <div class="design">
    <div class="design__steps">
      <div class="design__steps__t">
        <h2 class="design__h">{{ $t('visual_api_design') }}</h2>
        <div class="design__steps__icon">
          <div class="design__steps__icon-cx" v-if="addId" @click="handleReset('formValidate')">
            <Icon type="md-refresh" />
            {{ $t('redesign') }}
          </div>
          <span v-if="addId" class="design__steps__icon-s">|</span>
          <div class="design__steps__icon-gx" v-if="!addId" @click="addDraft('formValidate')">
            <Icon type="md-paper" />
            {{ $t('add_draft') }}
          </div>
          <div class="design__steps__icon-gx" v-else @click="updataDraft('formValidate')">
            <Icon type="md-paper" />
            {{ $t('update_draft') }}
          </div>
          <!-- <span class="design__steps__icon-s">|</span>
          <div class="design__steps__icon-sc" @click="handleSubmit('formValidate')">
            <Icon type="md-git-merge" />
            生成代码
          </div> -->
          <!-- <span class="design__steps__icon-s">|</span>
          <div>
            <Icon type="logo-github" />
            生成代码
          </div> -->
        </div>
      </div>
      <span class="design__steps__span"></span>
      <!-- <p>当前正在进行第 {{ current + 1 }} 步</p> -->
      <div class="design__steps__steps">
        <Steps :current="current" style="width: 60%">
            <Step :title="$t('one_api_design')"></Step>
            <Step :title="$t('two_create')"></Step>
            <Step :title="$t('three_save')"></Step>
            <!-- <Step title="第4步：查看接口"></Step> -->
        </Steps>
      </div>
    </div>
    <Row class="design__box">
      <!-- 接口设计 -->
      <div class="design__box__left">
            <!-- <p>接口名称、接口功能、接口参数、返回结构及结果示例。</p> -->
        <!-- <div style="display: flex;justify-content: center;">
            <div class="header-btn" v-if="addId" @click="handleReset('formValidate')"><Icon type="md-refresh" />重新设计</div>
            <div class="header-btn" v-if="!addId" @click="addDraft('formValidate')"><Icon type="md-clipboard" />添加草稿</div>
            <div class="header-btn" v-else @click="updataDraft('formValidate')"><Icon type="md-clipboard" />更新草稿</div>
            <Button type="primary"  style="border-radius:0;" @click="handleSubmit('formValidate')">生成代码</Button>
        </div> -->
        <!-- {{ $t('api_design_info') }} -->
        <div class="design__box__header">
            <p class="design__box__left-p">{{ $t('api_design_info') }}</p>
        </div>
        <!-- 表格 -->
        <div class="design__box__left-design">
          <Form ref="formValidate" class="design__box__left-form" :model="formValidate" :rules="ruleValidate">
            <FormItem :label="$t('design_00')">
              <RadioGroup v-model="formValidate.apiTypeGroup">
                <Radio label = '1'>{{ $t('shujujieapi') }}</Radio>
                <Radio label = '0'>{{ $t('pu_tong_jie_kou_api') }}</Radio>
              </RadioGroup>
            </FormItem>
            <div style="display: flex;align-items: flex-end;">
              <FormItem :label="$t('design_0')" prop="className" style="width:50%" >
                <Input @on-blur="apiHrefSkipCla" v-model="formValidate.className" :placeholder="$t('design_1')">
                  <span slot="prepend">App.</span>
                </Input>
              </FormItem>
              <p style="margin: 0px 5px 30px;">.</p>
              <FormItem prop="functionName" :label-width="0" style="width:50%">
                <Input @on-blur="apiHrefSkipFun" v-model="formValidate.functionName" :placeholder="$t('design_2')"></Input>
              </FormItem>
              <!-- <span style="line-height: 2rem;">格式：App.类名.方法名</span> -->
            </div>
            <FormItem :label="$t('design_3')" prop="moduleName">
              <Input v-model="formValidate.moduleName" :placeholder="$t('design_4')"></Input>
            </FormItem>
            <FormItem :label="$t('design_5')" prop="title">
              <Input v-model="formValidate.title" :placeholder="$t('design_6')"></Input>
            </FormItem>
            <FormItem :label="$t('design_7')" prop="desc">
              <Input v-model="formValidate.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}"></Input>
            </FormItem>

            <!-- 接口参数 -->
            <FormItem :label="$t('design_8')">
              <div>
                <Table border :columns="columns" style="width: 100%;" :data="formItemData">
                <template slot="name" slot-scope="{ row,index }" >
                  <Input v-model="formItemData[index].name" @on-blur="addInput(index)"></Input>
                </template>
                <template slot="type" class="type" slot-scope="{ row,index }" >
                  <Select :transfer="true" v-model="formItemData[index].type" @on-change="changeTypeDisabled($event,index)" style="width:100px">
                    <Option v-for="item in typeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                  </Select>
                </template>
                <template slot="require" slot-scope="{ row,index }" >
                  <Checkbox v-model="formItemData[index].require" @on-change="changeCheckbox($event,index)">{{ $t('design_9') }}</Checkbox>
                </template>
                <template slot="default" slot-scope="{ row,index }" >
                  <Input v-if="row.type !== 'bool'" :type="defaultType" v-model="formItemData[index].default"></Input>
                  <Select v-else :transfer="true" v-model="formItemData[index].default" @on-change="changeShowDisabled($event,index)" style="width:100px">
                    <Option v-for="item in showList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                  </Select>
                </template>
                <template slot="min" slot-scope="{ row,index }" >
                  <Input :type="defaultType" :disabled="row.type === 'bool'" v-model="formItemData[index].min"></Input>
                </template>
                <template slot="max" slot-scope="{ row,index }" >
                  <Input :type="defaultType" :disabled="row.type === 'bool'" v-model="formItemData[index].max"></Input>
                </template>
                <template slot="desc" slot-scope="{ row,index }" >
                  <Input v-model="formItemData[index].desc"></Input>
                </template>
                <template slot-scope="{ row,index }" slot="operation" class="operation">
                  <Button type="text" size="small" :disabled="index === 0" @click="upFieldOrder(index)">{{ $t('design_10') }}</Button>
                  <Button type="text" size="small" :disabled="index === formItemData.length - 1" @click="downFieldOrder(index)">{{ $t('design_11') }}</Button>
                  <Button type="text" size="small" v-if="formItemData.length > 2" style="color: red" @click="remove(index)">{{ $t('delete') }}</Button>
                </template>
              </Table>
              </div>
            </FormItem>
            <!-- 返回结果 -->
            <FormItem  :label="$t('design_12')">
              <div>
                <Table border :columns="columnsRes" style="width: 100%" :data="formItemResData">
                  <template slot="name" slot-scope="{ row,index }">
                    <Input v-model="formItemResData[index].name" @on-blur="addResInput(index)"></Input>
                  </template>
                  <template slot="type" class="type" slot-scope="{ row,index }">
                    <Select v-model="formItemResData[index].type" @on-change="changeResTypeDisabled($event,index)" :transfer="true" style="width:100px;">
                      <Option v-for="item in typeResList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                  </template>
                  <template slot="desc" slot-scope="{ row,index }">
                    <Input v-model="formItemResData[index].desc"></Input>
                  </template>
                  <template slot-scope="{ row,index }" slot="operation" class="operation">
                    <Button type="text" size="small" :disabled="index === 0" @click="upFieldOrderRes(index)">{{ $t('design_10') }}</Button>
                    <Button type="text" size="small" :disabled="index === formItemResData.length - 1" @click="downFieldOrderRes(index)">{{ $t('design_11') }}</Button>
                    <Button type="text" size="small" v-if="formItemResData.length > 2" style="color: red" @click="removeRes(index)">{{ $t('delete') }}</Button>
                  </template>
                </Table>
              </div>
            </FormItem>
            <!-- 接口返回示例 -->
            <FormItem style="" :label="$t('design_13')" prop="json">
              <div>
              <Input v-model="formValidate.json" style="width:100%" type="textarea" :placeholder="$t('design_13_1')"></Input>
              </div>
            </FormItem>
          </Form>
        </div>
      </div>
      <!-- 生成代码 -->
      <div class="design__box__right">
        <div class="design__box__right-generate">
          <!-- 接口路劲 -->
          <div class="design__box__right-generate-path">
            <div class="design__box__right-generate-path-p">
              <p class="design__box__right-generate-path-p-p">{{ $t('design_14') }}</p>
            </div>
            <div class="design__box__right-generate-path-i">
              <Input disabled v-model="generatePath" style="width: 100%" />
            </div>
          </div>
          <!-- 接口代码 -->
          <div class="design__box__right-generate-code">
            <!-- <p>接口PHP代码：</p> -->
            <div class="design__box__right-generate-code-h">
              <p class="design__box__right-generate-code-h-p">{{ $t('design_15') }}</p>
            </div>
            <div class="design__box__right-generate-code-b">
              <div class="design__box__right-generate-code-b-s">
                <div>
                  <Button type="success" style="margin-right:10px;" @click="handleSubmit('formValidate')">{{ $t('design_16') }}</Button>
                  <Button type="primary" @click="saveCode">{{ $t('design_17') }}</Button>
                </div>
                <!-- <Button :disabled="saveCodeDisabled" style="margin-left: 8px" @click="lookApi">查看接口</Button> -->
                <Button @click="copyCode()">{{ $t('design_18') }}</Button>
              </div>
            </div>
            <div class="copyBox">
              <!-- <Input v-model="generateCode" id="copyGenerateCode"  readonly :autosize="{minRows: 20}" type="textarea" style="width: 100%" /> -->
              <codemirror ref="myCopyCode"  id="copyGenerateCode"  v-model="generateCode" :options="cmOptions"></codemirror>
              <!-- <div class="copyBox__btn" @click="copyCode()">复制</div> -->
              <!-- 保存和查看 -->
              <!-- <div class="copyBox__btn save" :disabled="saveCodeDisabled" type="warning" @click="saveCode">保存代码</div> -->
              <!-- <Button :disabled="saveCodeDisabled" style="margin-left: 8px" @click="lookApi">查看接口</Button> -->
              <!-- <a class="copyBox__btn check" target="_blank" :disabled="apiHrefDis" :href="apiHref" @click="lookApi">查看接口</a> -->
            </div>
          </div>
        </div>
      </div>
    </Row>
  </div>
</template>

<script>
import Vue from 'vue'
import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
import { AddApiDesign, CreateCodeTemplate, GetDraft, SaveAndCreateApi, UpdateApiDesign, DelApiDesign } from '@/api/techzones'
import { getToken } from '@/libs/util'
require('codemirror/mode/php/php.js')
require('codemirror/theme/eclipse.css')
export default {
  components: {
    codemirror
  },
  data () {
    return {
      kong: true,
      token: getToken(),
      defaultType: 'text',
      addId: 0,
      addTiem: false,
      current: 0, // 步骤条
      apiHref: '',
      apiHrefDis: true,
      saveCodeDisabled: true,
      typeDisabled: false,
      addIdTrue: false,
      isSaveCodeId: false,
      typeList: [
        {
          value: 'string',
          label: this.$t('design_19')
        },
        {
          value: 'int',
          label: this.$t('design_20')
        },
        {
          value: 'float',
          label: this.$t('design_21')
        },
        {
          value: 'bool',
          label: this.$t('design_22')
        }
      ], // 接口select选择器
      typeResList: [
        {
          value: 'string',
          label: this.$t('design_19')
        },
        {
          value: 'int',
          label: this.$t('design_20')
        },
        {
          value: 'float',
          label: this.$t('design_21')
        },
        {
          value: 'bool',
          label: this.$t('design_22')
        },
        {
          value: 'array',
          label: this.$t('design_24')
        },
        {
          value: 'pbject',
          label: this.$t('design_25')
        },
        {
          value: 'date',
          label: this.$t('design_26')
        }
      ], // 接口select选择器
      showList: [
        {
          value: 'true',
          label: 'true'
        },
        {
          value: 'false',
          label: 'false'
        }
      ],
      columns: [
        {
          title: this.$t('design_27'),
          key: 'name',
          slot: 'name',
          fixed: 'left',
          width: '100'
        },
        {
          title: this.$t('design_28'),
          key: 'type',
          slot: 'type',
          width: '120'
        },
        {
          title: this.$t('design_29'),
          key: 'require',
          slot: 'require',
          width: '100'
        },
        {
          title: this.$t('design_30'),
          key: 'default',
          slot: 'default',
          width: '120'
        },
        {
          title: this.$t('design_31'),
          key: 'min',
          slot: 'min',
          width: '100'
        },
        {
          title: this.$t('design_32'),
          key: 'max',
          slot: 'max',
          width: '100'
        },
        {
          title: this.$t('design_33'),
          key: 'desc',
          slot: 'desc',
          width: '100'
        },
        {
          title: this.$t('operation'),
          key: 'operation',
          slot: 'operation',
          width: '160',
          fixed: 'right',
          align: 'center'
        }
      ], // 接口参数表字段
      columnsRes: [
        {
          title: this.$t('design_35'),
          fixed: 'left',
          key: 'name',
          slot: 'name'
        },
        {
          title: this.$t('design_36'),
          key: 'type',
          slot: 'type'
        },
        {
          title: this.$t('design_37'),
          key: 'desc',
          slot: 'desc'
        },
        {
          title: this.$t('operation'),
          key: 'operation',
          slot: 'operation',
          width: '160',
          fixed: 'right',
          align: 'center'
        }
      ], // 返回结果表字段
      // formItemDisabled: [{}], // 接口参数disabled
      formItemData: [{}], // 接口参数数组
      formItemResData: [{}], // 返回结果数组
      formValidate: {
        apiTypeGroup: '1',
        className: '',
        functionName: '',
        moduleName: this.$t('design_3'),
        title: this.$t('design_38'),
        desc: this.$t('design_7'),
        json: `{
    "ret": 200,
    "data": null,
    "msg": ""
}`
      }, // 规则变量
      ruleValidate: {
        className: [
          { required: true, message: this.$t('design_39'), trigger: 'blur', pattern: /^[a-zA-Z][a-zA-Z0-9]*$/ }
        ],
        functionName: [
          { required: true, message: this.$t('design_40'), trigger: 'blur', pattern: /^[A-Za-z0-9_]+$/ }
        ],
        moduleName: [
          { required: true, message: this.$t('design_41'), trigger: 'blur', pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/ }
        ],
        title: [
          { required: true, message: this.$t('design_42'), trigger: 'blur', pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/ }
        ],
        formItemData: [
          { required: true, message: this.$t('design_43'), trigger: 'blur' }
        ],
        formItemResData: [
          { required: true, message: this.$t('design_44'), trigger: 'blur' }
        ]
      }, // 验证规则
      generatePath: '', // 接口文件路径
      generateCode: '', // 接口PHP代码
      cmOptions: {
        mode: 'text/x-php', // 代码类型
        lineNumbers: true, // 行号
        readOnly: true, // 只读
        theme: 'eclipse' // 主题
      }
    }
  },
  created () {
    this.getDragtFun()
  },
  mounted () {
    window.onbeforeunload = function (e) {
      e = e || window.event
      // 兼容IE8和Firefox 4之前的版本
      if (e) {
        e.returnValue = this.$t('design_45')
      }
      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
      return this.$t('design_45')
    }
  },
  destroyed () {
    window.onbeforeunload = null
  },
  methods: {
    /* api地址 */
    apiHrefSkipCla () {
      var regexClass = new RegExp(/^[a-zA-Z][a-zA-Z0-9]*$/)
      if (!regexClass.test(this.formValidate.className)) {
        this.$Message.warning(this.$t('design_46'))
      }
    },
    /* api地址Function */
    apiHrefSkipFun () {
      var regexFun = new RegExp(/^[A-Za-z0-9_]+$/)
      if (regexFun.test(this.formValidate.functionName)) {
        if (this.formValidate.className) {
          this.apiHrefDis = false
          this.apiHref = '/docs.php?service=App.' + this.formValidate.className + '.' + this.formValidate.functionName + '&detail=1' + '&type=fold'
        } else {
          this.$Message.warning(this.$t('design_46'))
        }
      } else {
        this.$Message.warning(this.$t('design_47'))
      }
    },
    /* 获取已有草稿 */
    getDragtFun () {
      const data = new FormData()
      data.append('access_token', this.token)
      GetDraft(data).then(res => {
        if (res.ret === 200 && res.data.has_draft) {
          this.addTiem = true
          const dataObj = res.data.draft
          this.addId = dataObj.id
          this.addTiemData = dataObj.add_time
          let apiName = []
          apiName = dataObj.api_name.split('.')
          this.formValidate.className = apiName[1]
          this.formValidate.functionName = apiName[2]
          this.formValidate.moduleName = dataObj.api_modules
          this.formValidate.title = dataObj.api_title
          if (dataObj.api_desc !== 'null') {
            this.formValidate.desc = dataObj.api_desc
          }
          if (dataObj.api_request_params !== '[]') {
            this.formItemData = JSON.parse(dataObj.api_request_params)
          }
          if (dataObj.api_response_params !== '[]') {
            this.formItemResData = JSON.parse(dataObj.api_response_params)
          }
          if (dataObj.api_response_example !== '[]') {
            this.formValidate.json = dataObj.api_response_example
          }
          if (this.formItemData[0].name) {
            this.formItemData.push({})
          }
          if (this.formItemResData[0].name) {
            this.formItemResData.push({})
          }
        }
      })
    },
    /* 接口参数select选项改变 */
    changeTypeDisabled (event, index) {
      this.formItemData[index].min = ''
      this.formItemData[index].max = ''
      this.formItemData[index].type = event
      if (event === 'bool') {
        this.formItemData[index].min = ''
        this.formItemData[index].max = ''
      }
    },
    changeShowDisabled (event, index) {
      this.formItemData[index].default = event
    },
    /* 结果select选项改变 */
    changeResTypeDisabled (event, index) {
      this.formItemResData[index].type = event
    },
    /* 是否必选 */
    changeCheckbox (event, index) {
      this.formItemData[index].require = event
    },
    /* 添加草稿设计 */
    addDraft (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          const formItemDataArr = []
          const formItemResDataArr = []
          for (let i = 0; i < this.formItemData.length - 1; i++) {
            formItemDataArr.push(this.formItemData[i])
          }
          for (let i = 0; i < this.formItemResData.length - 1; i++) {
            formItemResDataArr.push(this.formItemResData[i])
          }
          const data = new FormData()
          data.append('access_token', this.token)
          data.append('api_name', 'App.' + this.formValidate.className + '.' + this.formValidate.functionName)
          data.append('api_modules', this.formValidate.moduleName)
          data.append('api_title', this.formValidate.title)
          if (this.formValidate.desc === '') {
            data.append('api_desc', null)
          } else {
            data.append('api_desc', this.formValidate.desc)
          }
          if (formItemDataArr.length !== 0) {
            data.append('api_request_params', JSON.stringify(formItemDataArr))
          }
          if (formItemResDataArr.length !== 0) {
            data.append('api_response_params', JSON.stringify(formItemResDataArr))
          }
          if (this.formValidate.json !== '') {
            data.append('api_response_example', this.formValidate.json)
          }
          AddApiDesign(data).then(res => {
            if (res.ret === 200 && res.data.code) {
              this.addIdTrue = true
              this.addId = res.data.id
              this.$Message.success(this.$t('add_successfully'))
              if (this.isSaveCodeId) {
                const saveData = new FormData()
                saveData.append('access_token', this.token)
                saveData.append('id', this.addId)
                saveData.append('is_data_api', this.formValidate.apiTypeGroup === '1' ? 1 : 2)
                SaveAndCreateApi(saveData).then(res => {
                  if (res.ret === 200) {
                    this.$Message.success(this.$t('design_61'))
                  } else {
                    this.$Message.warning(res.msg)
                  }
                })
                this.isSaveCodeId = false
              }
            } else {
              this.$Message.warning(res.data.msg)
            }
          })
        } else {
          this.$Message.error(this.$t('design_48'))
        }
      })
    },
    /* 更新接口设计 */
    updataDraft (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          const formItemDataArr = []
          const formItemResDataArr = []
          for (let i = 0; i < this.formItemData.length - 1; i++) {
            formItemDataArr.push(this.formItemData[i])
          }
          for (let i = 0; i < this.formItemResData.length - 1; i++) {
            formItemResDataArr.push(this.formItemResData[i])
          }
          const data = new FormData()
          data.append('access_token', this.token)
          data.append('id', this.addId)
          data.append('api_name', 'App.' + this.formValidate.className + '.' + this.formValidate.functionName)
          data.append('api_modules', this.formValidate.moduleName)
          data.append('api_title', this.formValidate.title)
          if (this.formValidate.desc === '') {
            data.append('api_desc', null)
          } else {
            data.append('api_desc', this.formValidate.desc)
          }
          if (formItemDataArr.length !== 0) {
            data.append('api_request_params', JSON.stringify(formItemDataArr))
          }
          if (formItemResDataArr.length !== 0) {
            data.append('api_response_params', JSON.stringify(formItemResDataArr))
          }
          if (this.formValidate.json !== '') {
            data.append('api_response_example', this.formValidate.json)
          }
          UpdateApiDesign(data).then(res => {
            if (res.ret === 200) {
              if (res.data.isUpdate) {
                this.current = 1
                this.$Message.success(res.data.msg)
              } else {
                this.$Message.warning(res.data.msg)
              }
            } else {
              this.$Message.warning(res.msg)
            }
          })
        } else {
          this.$Message.error(this.$t('design_48'))
        }
      })
    },
    /* 生成代码 */
    handleSubmit () {
      // if (this.formItemData[0].name && this.formItemResData[0].name && this.formValidate.json) {
      const formItemDataArr = []
      const formItemResDataArr = []
      for (let i = 0; i < this.formItemData.length - 1; i++) {
        formItemDataArr.push(this.formItemData[i])
      }
      for (let i = 0; i < this.formItemResData.length - 1; i++) {
        formItemResDataArr.push(this.formItemResData[i])
      }
      formItemResDataArr.forEach(item => {
        if (item.name) {
          if (!item.type) {
            return this.$Message.warning(this.$t('design_49'))
          }
        }
      })
      const data = new FormData()
      data.append('access_token', this.token)
      if (this.formValidate.className && this.formValidate.functionName) {
        data.append('api_name', 'App.' + this.formValidate.className + '.' + this.formValidate.functionName)
      }
      // data.append('api_name', 'App.' + this.formValidate.className + '.' + this.formValidate.functionName)
      if (this.formValidate.moduleName) {
        data.append('api_modules', this.formValidate.moduleName)
      }
      if (this.formValidate.title) {
        data.append('api_title', this.formValidate.title)
      }
      if (this.formValidate.desc) {
        data.append('api_desc', this.formValidate.desc)
      }
      if (formItemDataArr) {
        data.append('api_request_params', JSON.stringify(formItemDataArr))
      }
      if (formItemResDataArr) {
        data.append('api_response_params', JSON.stringify(formItemResDataArr))
      }
      if (this.formValidate.json) {
        data.append('api_response_example', this.formValidate.json)
      }
      data.append('is_data_api', this.formValidate.apiTypeGroup)
      CreateCodeTemplate(data).then(res => {
        if (res.ret === 200) {
          this.current = 2
          this.saveCodeDisabled = false
          this.generatePath = res.data.path
          this.generateCode = res.data.code
          this.$Message.success(this.$t('design_52'))
        } else {
          this.$Message.warning(res.msg)
        }
      })
      /* if (this.formValidate.apiTypeGroup === '1') {
        this.$Modal.confirm({
          title: '确认操作',
          content: '当前接口类型为数据接口，仅在首次保存时根据接口参数创建数据库表。创建后可自行调整表字段，是否继续保存？',
          onOk: () => {
            this.addDraft('formValidate')
            console.log(this.addId, '---------新的ip')
            if (this.addId) {
              data.append('is_data_api', 1)
              CreateCodeTemplate(data).then(res => {
                if (res.ret === 200) {
                  this.current = 2
                  this.saveCodeDisabled = false
                  this.generatePath = res.data.path
                  this.generateCode = res.data.code
                  this.$Message.success('生成成功')
                } else {
                  this.$Message.warning(res.msg)
                }
              })
            }
          },
          onCancel: () => {
            this.$Message.warning('取消操作')
          }
        })
      } else {
        this.addDraft('formValidate')
        if (this.addId) {
          data.append('is_data_api', 0)
          CreateCodeTemplate(data).then(res => {
            if (res.ret === 200) {
              this.current = 2
              this.saveCodeDisabled = false
              this.generatePath = res.data.path
              this.generateCode = res.data.code
              this.$Message.success('生成成功')
            } else {
              this.$Message.warning(res.msg)
            }
          })
        }
      } */
    },
    /* 新增参数一行参数列表 */
    addInput (index) {
      if (index === this.formItemData.length - 1) {
        if (this.formItemData[index].name) {
          this.formItemData.push({})
          // this.formItemDisabled.push({})
        }
      }
    },
    /* 新增结果一行参数列表 */
    addResInput (index) {
      if (index === this.formItemResData.length - 1) {
        if (this.formItemResData[index].name) {
          this.formItemResData.push({})
        }
      }
    },
    /* 上移 */
    upFieldOrder (index) {
      let temp = this.formItemData[index - 1]
      Vue.set(this.formItemData, index - 1, this.formItemData[index])
      Vue.set(this.formItemData, index, temp)
    },
    /* 下移 */
    downFieldOrder (index) {
      let i = this.formItemData[index + 1]
      Vue.set(this.formItemData, index + 1, this.formItemData[index])
      Vue.set(this.formItemData, index, i)
    },
    /* Res上移 */
    upFieldOrderRes (index) {
      let temp = this.formItemResData[index - 1]
      Vue.set(this.formItemResData, index - 1, this.formItemResData[index])
      Vue.set(this.formItemResData, index, temp)
    },
    /* Res下移 */
    downFieldOrderRes (index) {
      let i = this.formItemResData[index + 1]
      Vue.set(this.formItemResData, index + 1, this.formItemResData[index])
      Vue.set(this.formItemResData, index, i)
    },
    remove (e) {
      this.formItemData.splice(e, 1)
    },
    removeRes (e) {
      this.formItemResData.splice(e, 1)
    },
    /* 保存代码 */
    saveCode () {
      const data = new FormData()
      data.append('access_token', this.token)
      data.append('id', this.addId)
      if (this.addId === 0) {
        this.isSaveCodeId = true
        // this.addDraft('formValidate')
        const formItemDataArr = []
        const formItemResDataArr = []
        for (let i = 0; i < this.formItemData.length - 1; i++) {
          formItemDataArr.push(this.formItemData[i])
        }
        for (let i = 0; i < this.formItemResData.length - 1; i++) {
          formItemResDataArr.push(this.formItemResData[i])
        }
        formItemResDataArr.forEach(item => {
          if (item.name) {
            if (!item.type) {
              return this.$Message.warning(this.$t('design_49'))
            }
          }
        })
        const data = new FormData()
        data.append('access_token', this.token)
        if (this.formValidate.className && this.formValidate.functionName) {
          data.append('api_name', 'App.' + this.formValidate.className + '.' + this.formValidate.functionName)
        }
        // data.append('api_name', 'App.' + this.formValidate.className + '.' + this.formValidate.functionName)
        if (this.formValidate.moduleName) {
          data.append('api_modules', this.formValidate.moduleName)
        }
        if (this.formValidate.title) {
          data.append('api_title', this.formValidate.title)
        }
        if (this.formValidate.desc) {
          data.append('api_desc', this.formValidate.desc)
        }
        if (formItemDataArr) {
          data.append('api_request_params', JSON.stringify(formItemDataArr))
        }
        if (formItemResDataArr) {
          data.append('api_response_params', JSON.stringify(formItemResDataArr))
        }
        if (this.formValidate.json) {
          data.append('api_response_example', this.formValidate.json)
        }
        if (this.formValidate.apiTypeGroup === '1') {
          this.$Modal.confirm({
            title: this.$t('design_50'),
            content: this.$t('design_51'),
            onOk: () => {
              this.addDraft('formValidate')
              data.append('is_data_api', 1)
              CreateCodeTemplate(data).then(res => {
                if (res.ret === 200) {
                  this.current = 2
                  this.saveCodeDisabled = false
                  this.generatePath = res.data.path
                  this.generateCode = res.data.code
                  /* 生成接口 */
                  /* SaveAndCreateApi().then(res => {

                }) */
                  this.$Message.success(this.$t('design_52'))
                } else {
                  this.$Message.warning(res.msg)
                }
              })
            },
            onCancel: () => {
              this.$Message.warning(this.$t('design_53'))
            }
          })
        } else {
          this.addDraft('formValidate')
          data.append('is_data_api', 0)
          CreateCodeTemplate(data).then(res => {
            if (res.ret === 200) {
              this.current = 2
              this.saveCodeDisabled = false
              this.generatePath = res.data.path
              this.generateCode = res.data.code
              this.$Message.success(this.$t('design_52'))
            } else {
              this.$Message.warning(res.msg)
            }
          })
        }
      } else {
        this.handleSubmit('formValidate')
        SaveAndCreateApi(data).then(res => {
          if (res.ret === 200) {
            if (res.data.isExists) {
              this.$Modal.confirm({
                title: this.$t('design_54'),
                content: '<p>'+  this.$t('design_55')  +'</p>',
                onOk: () => {
                  this.updataDraft('formValidate')
                  data.append('is_force', 2)
                  data.append('is_data_api', this.formValidate.apiTypeGroup)
                  SaveAndCreateApi(data).then(res => {
                    if (res.ret === 200) {
                      if (res.data.isCreate) {
                        this.$Message.success(this.$t('design_56'))
                        this.$Message.success(res.data.exampleMsg)
                        this.current = 3
                      }
                    }
                  })
                },
                onCancel: () => {
                  this.$Message.info(this.$t('design_57'))
                }
              })
            } else {
              this.$Message.warning(res.data.msg)
              this.$Message.warning(res.data.exampleMsg)
            }
          } else {
            this.$Message.warning(res.msg)
          }
        })
      }
    },
    /* 查看接口 */
    lookApi () {
      this.current = 4
    },
    /* 复制PHP代码 */
    copyCode () {
      if (this.generateCode) {
        var Url2 = this.generateCode
        var oInput = document.createElement('textarea')
        oInput.value = Url2
        document.body.appendChild(oInput)
        oInput.select() // 选择对象
        document.execCommand('Copy') // 执行浏览器复制命令
        this.$Message.success(this.$t('design_58'))
      } else {
        this.$Message.warning(this.$t('design_59'))
      }
    },
    /* 重新设计 */
    handleReset (name) {
      this.$Modal.confirm({
        title: this.$t('design_50'),
        content: '<p>' + this.$t('design_60') + '</p>',
        onOk: () => {
          const data = new FormData()
          data.append('access_token', this.token)
          data.append('id', this.addId)
          DelApiDesign(data).then(res => {
            if (res.ret === 200 && res.data.code) {
              this.addId = 0
              this.apiHrefDis = true
              this.$refs[name].resetFields()
              this.formItemData = [{}]
              this.formItemResData = [{}]
              this.formItemData.forEach(item => {
                item.min = ''
                item.min = ''
              })
              this.current = 0
              this.generatePath = ''
              this.generateCode = ''
              this.saveCodeDisabled = true
              this.addTiem = false
              this.$Message.success(this.$t('design_62'))
            } else {
              if (res.msg) {
                this.$Message.warning(res.msg)
              } else {
                this.$Message.warning(res.data.msg)
              }
            }
          })
        },
        onCancel: () => {
          this.$Message.info(this.$t('design_53'))
        }
      })
    }
  }
}
</script>

<style  lang='scss' scoped>
.design{
  &__h{
    color: #333333;
    font-size:16px;
    font-family:PingFangSC-Medium,PingFang SC;
    font-weight:600;
  }
  &__steps{
    height:158px;
    background:rgba(255,255,255,1);
    box-shadow:0px 0px 30px 0px rgba(0,0,0,0.05);
    border-radius:10px;
    margin-bottom: 20px;
    &__t{
      height: 55px;
      margin: 0 30px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    &__icon{
      display: flex;
      align-items: center;
      &-s{
        color: #E9E9E9;
        margin: 0 16px;
      }
      &-cx, &-gx, &-sc{
        cursor: pointer;
      }
      &-cx:hover, &-gx:hover, &-sc:hover{
        color: #F4AE22;
      }
    }
    &__span{
      display: block;
      background: #E9E9E9;
      height: 1px;
      width: 100%;
    }
    &__steps{
      height: 102px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  &__box{
    &__left{
      &-p{
        display: flex;
        align-items: flex-end;
        h3{
          font-size: 18px;
          margin-right: 5px;
        }
      }
      &-design{
        // margin-right: 40px;
        // border: 1px solid rgb(197, 197, 197);
        background: #fff;
        &-form{
          display: flex
        }
      }
    }
    &__right{
      // background: #fff;
      &-p{
        display: flex;
        align-items: flex-end;
        h3{
          font-size: 18px;
          margin-right: 5px;
        }
      }
      &-generate{
        // border: 1px solid rgb(197, 197, 197);
        // height: auto;
        &-path{
          margin-bottom: 12px;
          display: flex;
          flex-direction: column;
          height: 118px;
          border-radius: 10px;
          background-color: #fff;
          margin-bottom: 20px;
          &-p{
            height: 55px;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #E9E9E9;
            &-p{
              font-size:16px;
              font-family:PingFangSC-Medium,PingFang SC;
              font-weight:500;
              color:rgba(51,51,51,1);
              margin: 0 20px;
            }
          }
          &-i{
            display: flex;
            height: 62px;
            align-items: center;
            margin: 0 18px;
          }
        }
        &-code{
          // margin:0 20px;
          border-radius: 10px;
          background-color: #fff;
          &-h{
            height: 55px;
            border-bottom: 1px solid #E9E9E9;
            display: flex;
            align-items: center;
            &-p{
              font-size:16px;
              font-family:PingFangSC-Medium,PingFang SC;
              font-weight:500;
              color:rgba(51,51,51,1);
              margin: 0 20px;
            }
          }
          &-b{
            height: 67px;
            margin: 0 18px;
            display: flex;
            align-items: center;
            &-s{
              width: 100%;
              display: flex;
              justify-content: space-between;
            }
          }
        }
        &-btn{
          // margin: 30px 0;
          padding: 30px 0 24px;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }
}
.CodeMirror-scroll{
  margin-right: 0;
}
.copyBox{
  position: relative;
  margin: 0 20px;
  padding-bottom: 30px;
  &__btn{
    z-index: 99;
    display: block;
    position: absolute;
    right: 15px;
    top: 35px;
    font-size: 12px;
    color: #4d4d4d;
    background-color: white;
    padding: 2px 8px;
    margin: 8px;
    border-radius: 4px;
    cursor: pointer;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05), 0 2px 4px rgba(0,0,0,0.05);
  }
}
.CodeMirror{
  height: 800px;
}
.design_box_header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #195c92;
  padding:  5px 12px;
  color: #fff;
}

.ivu-form-item {
  margin-bottom: 12px;
}
.CodeMirror-scroll {
  background: #eee;
}

.design__box {
  // box-shadow: 0 1px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  &__left{
    width: 67%;
    background: #fff;
    border-radius: 10px;
    &-p{
      margin-left: 24px;
      font-size:16px;
      font-family:PingFangSC-Medium,PingFang SC;
      font-weight:500;
      color:rgba(51,51,51,1);
    }
    &-form{
      margin: 0 30px;
    }
  }
  &__header{
    height: 60px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #E9E9E9;
    margin-bottom: 25px;
  }
  &__right{
    width: 30%;
  }
}

/* Form */
.ivu-form .ivu-form-item-label{
  width: 100%;
  text-align: left;
}
.ivu-form-item{
  margin-bottom: 30px;
}
/*  */
.copyBox__btn.save {
  top: 4px
}
.copyBox__btn.check {
  top: 35px
}
.header-btn {
    margin-right: 14px;
    font-size: 14px;
    line-height: 30px;
    cursor: pointer;
}
.ivu-steps .ivu-steps-title{
  margin-top: 3px;
}

.ivu-row:before, .ivu-row:after{
  content: none;
}
</style>
