<template>
  <div class="apiTestAdd">
    <div class="apiTestAdd__h">
      <p class="apiTestAdd__h--p">{{ $t('example_edition') }}</p>
    </div>
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="140" class="apiTestAdd__form">
      <!-- 用例方法 -->
      <FormItem :label="$t('test_1')" prop="testName" >
        <Input clearable style="width: 75%" v-model="formValidate.testName">
        </Input>
      </FormItem>
      <!-- 接口路径 -->
      <FormItem :label="$t('apitest_1')" prop="apiPath">
        <Input clearable style="width: 75%"  v-model="formValidate.apiPath"></Input>
      </FormItem>
      <!-- 接口名称 -->
      <FormItem :label="$t('test_3')" style="position: relative;">
        <!-- <Input style="width: 90%"  v-model="formValidate.title" placeholder="一句话标题"></Input> -->
        <span style="color:red;font-family: SimSun;position: absolute;left: -82px;">*</span>
        <Input clearable style="width: 75%" disabled v-model="apiModuleApiName"></Input>
      </FormItem>
      <!-- 添加token -->
      <FormItem :label="$t('look_5')" prop="acToken" style="position: relative;">
        <!-- <Input  v-model="access_token"></Input> -->
        <span style="color:red;font-family: SimSun;position: absolute;left: -132px;">*</span>
        <Select clearable style="width: 75%" v-model="configName"  @on-change="changeConfig">
          <Option v-for="item in configList" :value="item.id" :label="item.title"  :key="item.title">{{ item.title }}</Option>
        </Select>
        <Button @click="asToken = true" type="text"><p>{{ $t('apitest_2') }}</p></Button>
      </FormItem>
      <!-- 获取token -->
      <Modal v-model="asToken">
        <p slot="header" style="font-size:16px;text-align:center">
            <span>{{ $t('apitest_3') }}</span>
        </p>
        <div style="display: flex;flex-wrap: wrap;justify-content: center;">
            <FormItem :label="$t('apitest_4')" class="formItemStyle" prop="asTokenName" :label-width="110">
              <div class="formItemStyle__box">
                <span class="star" style="left: -80px;">*</span>
                <div style="display: flex;">
                  <!-- <Input  v-model="formValidate.asTokenName"></Input> -->
                  <Input clearable v-model="formValidate.asTokenName">
                  </Input>
                </div>
              </div>
            </FormItem>
            <FormItem :label="$t('apitest_5')" class="formItemStyle" id="formItemStyleWay" :label-width="110">
              <div class="formItemStyle__box" style="margin-right: 50px;">
                <div style="position:relative">
                <Select clearable v-model="formValidate.asApiToken">
                  <Option v-for="item in asApiTokenList" :value="item.value" :key="item.title">{{ item.label }}</Option>
                </Select>
                <a target="_blank" style="position: absolute;width: 50px;" :href="formValidate.asApiToken === 'App.Auth.ApplyToken' ?  '/docs.php?service=App.Auth.ApplyToken&detail=1&type=fold' :' /docs.php?service=App.Auth.UserLogin&detail=1&type=fold'">{{ $t('apitest_6') }}</a>
                <!-- <a target="_blank" v-else style="position: absolute;width: 50px;" href="http://pro.api.phalapi.net/docs.php?service=App.Auth.UserLogin&detail=1&type=fold">接口文档</a> -->
                </div>
              </div>
            </FormItem>
            <!-- App.Auth.ApplyToken -->
            <div v-if="formValidate.asApiToken === 'App.Auth.ApplyToken'" style="width:100%">
              <FormItem label="app_key：" class="formItemStyle" prop="app_keyy" :label-width="110">
              <div class="formItemStyle__box">
                <span class="star" style="left: -80px;top:3px;">*</span>
                <div>
                  <Input clearable v-model="formValidate.app_key"></Input>
                </div>
              </div>
              </FormItem>
              <FormItem label="app_secret：" class="formItemStyle" prop="app_secret" :label-width="110">
              <div class="formItemStyle__box">
                <span class="star" style="left: -80px;top:3px;">*</span>
                <div>
                  <Input clearable v-model="formValidate.app_secret"></Input>
                </div>
              </div>
              </FormItem>
              <FormItem label="uid：" class="formItemStyle" :label-width="110">
              <div class="formItemStyle__box">
                <div>
                  <Input clearable v-model="formValidate.uid"></Input>
                </div>
              </div>
              </FormItem>
            </div>
            <!-- App.Auth.UserLogin -->
            <div v-else style="width:100%">
              <FormItem label="username：" class="formItemStyle" prop="username" :label-width="110">
                <div class="formItemStyle__box">
                  <span class="star" style="left: -80px;top:3px;">*</span>
                  <div>
                    <Input clearable v-model="formValidate.username"></Input>
                  </div>
                </div>
              </FormItem>
              <FormItem label="password：" class="formItemStyle" prop="password" :label-width="110">
                <div  class="formItemStyle__box">
                  <span class="star" style="left: -80px;top:3px;">*</span>
                  <div>
                    <Input clearable v-model="formValidate.password"></Input>
                  </div>
                </div>
              </FormItem>
              <FormItem label="app_key：" class="formItemStyle" :label-width="110">
                <div class="formItemStyle__box">
                  <span class="star" style="left: -80px;top:3px;">*</span>
                  <div>
                    <Input clearable v-model="formValidate.ulapp_key"></Input>
                  </div>
                </div>
              </FormItem>
            </div>
        </div>
        <div slot="footer" style="display: flex;justify-content: center;align-items: center;">
            <Button v-if="formValidate.asApiToken === 'App.Auth.ApplyToken'" type="warning" @click="addTokenApp">{{$t('add')}}</Button>
            <Button v-else type="warning" @click="addTokenUl">{{$t('add')}}</Button>
        </div>
      </Modal>
      <!-- 接口参数 -->
      <FormItem  label="接口参数：" prop="formItemData">
        <div style="margin-left: -110px;width:85%">
          <Table border :columns="columns" :data="formItemData">
            <template slot="name" slot-scope="{ row,index }" >
              <!-- <p> {{ row.name }} </p> -->
              <Input clearable v-model="formItemData[index].name" @on-blur="addInput(index)"></Input>
            </template>
            <template slot="require" slot-scope="{ row,index }" >
              <p v-if="index+1 <= formItemResLength" :style="{'color': row.require === '必须' ? 'red' : 'black'}">{{ row.require }}</p>
              <!-- <p v-else> 可选 </p> -->
              <div v-else>
                <Select clearable v-model="formItemData[index].require" @on-change="changeType($event,index)" :transfer="true" style="width:100px;">
                <Option v-for="item in requirArr" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
              </div>
            </template>
            <template slot="val" slot-scope="{ row,index }" >
              <Input clearable v-model="formItemData[index].value" :placeholder="row.desc"></Input>
            </template>
          </Table>
        </div>
      </FormItem>
      <!-- 返回结果 -->
      <FormItem  :label="$t('look_7')">
        <div style="margin-left: -110px;width:85%;">
          <Table border :columns="columnsRes" style="width: 100%" :data="formItemResData">
            <template slot="name" slot-scope="{ row,index }">
              <p v-if="!row.name">{{ row.name }}</p>
              <Input clearable v-model="formItemResData[index].name" @on-blur="addResInput(index)"></Input>
            </template>
            <template slot="operate" slot-scope="{ row,index }">
              <Select v-model="formItemResData[index].operate" @on-change="changeResType($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="expect" slot-scope="{ row,index }">
              <Input clearable v-model="formItemResData[index].expect"></Input>
            </template>
            <template slot-scope="{ row,index }" slot="operation" class="operation">
              <Button type="text" :disabled="index === 0" size="small" style="color: red" @click="removeRes(index)">{{$t('detele')}}</Button>
            </template>
          </Table>
        </div>
      </FormItem>
      <!-- 添加人 -->
      <FormItem :label="$t('look_8')">
        <Input clearable style="width: 75%" disabled v-model="formValidate.editName"></Input>
      </FormItem>
      <FormItem :label-width=0>
        <div style="display: flex;margin:30px 0px 0px 140px;">
          <Button type="primary" style="margin-right: 20px;" @click="handleSubmit('formValidate')">{{$t('save')}}</Button>
          <router-link :to="{path: '/techzones/apitest/test'}">
            <Button>{{$t('back')}}</Button>
          </router-link>
        </div>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import { GetTestSample, AddAtConfig, EditTestSample, GetAtConfigList } from '@/api/techzones'
import { getToken } from '@/libs/util'
export default {
  name: '',
  data () {
    return {
      token: getToken(),
      compileId: 0,
      apiModule: '',
      apiModuleApi: '',
      apiModuleList: [],
      apiModuleApiList: [],
      apiModuleApiName: '',
      asToken: false,
      access_token: '',
      firstRes: '=',
      configName: 0,
      configAll: 0,
      configList: [],
      removeDis: true,
      formItemResDis: true,
      paramBool: false,
      asApiTokenList: [
        {
          value: 'App.Auth.ApplyToken',
          label: 'App.Auth.ApplyToken'
        },
        {
          value: 'App.Auth.UserLogin',
          label: 'App.Auth.UserLogin'
        }
      ],
      columns: [
        {
          title: this.$t('design_27'),
          key: 'name',
          slot: 'name',
          align: 'center'
        },
        {
          title: this.$t('apitest_7'),
          key: 'require',
          slot: 'require',
          align: 'center'
        },
        {
          title: this.$t('look_19'),
          key: 'val',
          slot: 'val',
          align: 'center'
        }
      ],
      columnsRes: [
        {
          title: this.$t('look_20'),
          key: 'name',
          slot: 'name',
          align: 'center'
        },
        {
          title: this.$t('look_21'),
          key: 'operate',
          slot: 'operate',
          align: 'center'
        },
        {
          title: this.$t('look_22'),
          key: 'expect',
          slot: 'expect',
          align: 'center'
        },
        {
          title: this.$t('operation'),
          key: 'operation',
          slot: 'operation',
          align: 'center'
        }
      ],
      requirArr: [
        {
          value: '必须',
          label: $t('required')
        },
        {
          value: '可选',
          label: $t('choosable')
        }
      ],
      formItemData: [],
      formItemDataArr: [],
      formItemResLength: 0,
      typeResList: [
        {
          value: '=',
          label: this.$t('apitest_8'),
          align: 'center'
        },
        {
          value: '!=',
          label: this.$t('apitest_9'),
          align: 'center'
        },
        {
          value: '>',
          label: this.$t('apitest_10'),
          align: 'center'
        },
        {
          value: '<',
          label: this.$t('apitest_11'),
          align: 'center'
        },
        {
          value: '>=',
          label: this.$t('apitest_12'),
          align: 'center'
        },
        {
          value: '<=',
          label: this.$t('apitest_13'),
          align: 'center'
        }
      ],
      formItemResData: [],
      formResDataArr: [],
      formValidate: {
        testName: '',
        apiPath: '',
        moduleName: '',
        asApiToken: 'App.Auth.ApplyToken',
        app_key: '',
        app_secret: '',
        uid: '',
        username: '',
        password: '',
        ulapp_key: '',
        editName: ''
      }, // 规则变量
      ruleValidate: {
        testName: [
          { required: true, message: this.$t('apitest_14'), trigger: 'blur' }
        ],
        apiPath: [
          { required: true, message: this.$t('apitest_15'), trigger: 'blur' },
          { message: this.$t('apitest_16'), pattern: /([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$/ }
        ]
      } // 验证规则
    }
  },
  created () {
    this.compileId = this.$route.query.id
    this.getConfig()
    this.getTestSample()
  },
  methods: {
    /* 获取配置 */
    getConfig () {
      const data = new FormData()
      data.append('access_token', this.token)
      GetAtConfigList(data).then(res => {
        if (res.ret === 200) {
          this.configAll = res.data.total
          this.configList = res.data.items
          this.getConfigAdd()
        }
      })
    },
    /* 增加后获取配置 */
    getConfigAdd () {
      const data = new FormData()
      data.append('access_token', this.token)
      data.append('perpage', this.configAll)
      // data.append('config_name', 'test_sample_')
      GetAtConfigList(data).then(res => {
        if (res.ret === 200) {
          this.configAll = res.data.total
          this.configList = res.data.items
        }
      })
    },
    /* 获取当前用例信息 */
    getTestSample () {
      const data = new FormData()
      data.append('access_token', this.token)
      data.append('id', this.compileId)
      GetTestSample(data).then(res => {
        if (res.ret === 200) {
          this.formValidate.testName = res.data.sample_name
          this.formValidate.apiPath = res.data.sample_host
          this.formValidate.moduleName = res.data.api_name
          this.formValidate.editName = res.data.uid
          this.apiModuleApiName = res.data.api_name
          this.configName = parseInt(res.data.access_token)
          if (res.data.sample_request === '[]') {
            this.formItemData.push({})
          } else {
            this.formItemData = JSON.parse(res.data.sample_request)
            this.formItemResLength = this.formItemData.length
            this.formItemData.push({})
          }
          this.formItemResData = JSON.parse(res.data.sample_response)
          this.formItemResData.push({})
        }
      })
    },
    /* 改变接口模块 */
    changeApiModule (data) {
      this.apiModuleApiList = []
      let apiModuleApiArr
      apiModuleApiArr = this.apiModuleList[data.value].items
      apiModuleApiArr.forEach(item => {
        this.apiModuleApiList.push(item)
        this.apiModuleApiList.forEach(item => {
          item.value = item.service
        })
      })
    },
    /* 新添加TokenApp */
    addTokenApp () {
      if (this.formValidate.asTokenName) {
        if (this.formValidate.app_key) {
          if (this.formValidate.app_secret) {
            const data = new FormData()
            data.append('access_token', this.token)
            data.append('title', this.formValidate.asTokenName)
            data.append('type', '2')
            const obj = {}
            obj.app_key = this.formValidate.app_key
            obj.app_secret = this.formValidate.app_secret
            if (this.formValidate.uid) {
              obj.uid = this.formValidate.uid
            }
            data.append('param', JSON.stringify(obj))
            AddAtConfig(data).then(res => {
              if (res.ret === 200 && res.data.isAdd) {
              // this.access_token = res.data.access_token
                this.$Message.success(res.data.msg)
                this.asToken = false
                this.getConfig()
              } else {
                if (res.msg) {
                  this.$Message.warning(res.msg)
                } else {
                  this.$Message.warning(this.$t('config_16'))
                }
              }
            })
          } else {
            this.$Message.warning(this.$t('config_15'))
          }
        } else {
          this.$Message.warning(this.$t('config_13'))
        }
      } else {
        this.$Message.warning(this.$t('apitest_21'))
      }
    },
    /* 新添加TokenUl */
    addTokenUl () {
      if (this.formValidate.asTokenName) {
        if (this.formValidate.username) {
          if (this.formValidate.password) {
            if (this.formValidate.ulapp_key) {
              const data = new FormData()
              data.append('access_token', this.token)
              data.append('title', this.formValidate.asTokenName)
              data.append('type', '1')
              const obj = {}
              obj.username = this.formValidate.username
              obj.password = this.formValidate.password
              obj.ulapp_key = this.formValidate.ulapp_key
              data.append('param', JSON.stringify(obj))
              AddAtConfig(data).then(res => {
                if (res.ret === 200 && res.data.isAdd) {
                  this.$Message.success(res.data.msg)
                  this.asToken = false
                  this.getConfig()
                } else {
                  if (res.msg) {
                    this.$Message.warning(res.msg)
                  } else {
                    this.$Message.warning(this.$t('config_14'))
                  }
                }
              })
            } else {
              this.$Message.warning(this.$t('config_13'))
            }
          } else {
            this.$Message.warning(this.$t('config_12'))
          }
        } else {
          this.$Message.warning(this.$t('config_11'))
        }
      } else {
        this.$Message.warning(this.$t('apitest_21'))
      }
    },
    /* 是否必选 */
    changeCheckbox (event, index) {
      this.formItemData[index].require = event
    },
    changeType (event, index) {
      this.formItemData[index].requir = event
    },
    /* 结果select选项改变 */
    changeResType (event, index) {
      this.formItemResData[index].judge = event
    },
    /* config改变 */
    changeConfig (data) {
      this.configName = data
    },
    /* 新增参数一行参数列表 */
    addInput (index) {
      if (index === this.formItemData.length - 1) {
        if (this.formItemData[index].name) {
          this.formItemData.push({})
        }
      }
    },
    /* 新增结果一行参数列表 */
    addResInput (index) {
      if (index === this.formItemResData.length - 1) {
        if (this.formItemResData[index].name) {
          this.formItemResData.push({})
        }
      }
    },
    removeRes (e) {
      this.formItemResData.splice(e, 1)
      if (this.formItemResData.length === 1) {
        this.formItemResData.push({})
      }
    },
    /* 传接口参数 */
    parameter () {
      if (this.formItemData.length > 0) {
        var paramArr = []
        for (let i in this.formItemData) {
          const { name: key, require, value } = this.formItemData[i]
          paramArr[i] = { name: key, require, value }
        }
        paramArr.forEach(item => {
          if (item.name) {
            if (!item.value) {
              item.value = ''
            }
          }
        })
        if (!paramArr[paramArr.length - 1].name) {
          this.formItemDataArr = paramArr.slice(0, -1)
          this.formItemDataArr = paramArr
        }
      } else {
        this.formItemDataArr = []
      }
    },
    /* 传预期结果参数 */
    resParameter () {
      if (this.formItemResData[0].name) {
        var arr = []
        for (let i in this.formItemResData) {
          const { name, operate, expect } = this.formItemResData[i]
          arr[i] = { name, operate, expect }
        }
        /* arr.forEach(item => {
          if (!item.expect) {
            delete item.expect
          }
        }) */
        if (!arr[arr.length - 1].name) {
          this.formResDataArr = arr.slice(0, -1)
        } else {
          this.formResDataArr = arr
        }
      } else {
        this.$Message.warning(this.$t('apitest_22'))
      }
    },
    /* 编辑用例 */
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.paramBool = false
          if (this.apiModuleApiName) {
            if (this.configName) {
              this.parameter()
              this.formItemDataArr = this.formItemDataArr.slice(0, -1)
              this.resParameter()
              /* 判断必要参数 */
              this.formItemDataArr.forEach(item => {
                // this.$Message.warning('此接口参数有必选参数，请填写该参数的参数值')
                if (item.name) {
                  if (!item.require) {
                    this.$Message.warning(this.$t('compile_1'))
                    this.paramBool = true
                  }
                }
                if (item.require === this.$t('required') && !item.value) {
                  this.$Message.warning(this.$t('apitest_23'))
                  this.paramBool = true
                }
              })
              /* this.formResDataArr.forEach(item => {
                if (item.operate) {
                  if (!item.expect) {
                    this.$Message.warning('请正确填写预期结果')
                  }
                } else {
                  this.$Message.warning('请正确填写判断操作')
                }
              }) */
              if (this.paramBool) {
                return this.$Message.warning(this.$t('apitest_24'))
              }
              const dataObj = new FormData()
              dataObj.append('access_token', this.token)
              dataObj.append('id', this.compileId)
              dataObj.append('sample_name', this.formValidate.testName)
              dataObj.append('api_name', this.apiModuleApiName)
              dataObj.append('sample_host', this.formValidate.apiPath)
              dataObj.append('sample_request', JSON.stringify(this.formItemDataArr))
              dataObj.append('sample_response', JSON.stringify(this.formResDataArr))
              dataObj.append('access_token_config', this.configName)
              EditTestSample(dataObj).then(res => {
                if (res.ret === 200 && res.data.isUpdate) {
                  this.$Message.success(res.data.msg)
                  this.$router.push({ name: 'apitestTest' })
                } else {
                  if (res.msg) {
                    this.$Message.warning(res.msg)
                  } else {
                    this.$Message.warning(res.data.msg)
                  }
                }
              })
            } else {
              this.$Message.warning(this.$t('apitest_25'))
            }
          } else {
            this.$Message.warning(this.$t('apitest_26'))
          }
        } else {
          this.$Message.warning(this.$t('design_48'))
        }
      })
    }
  }
}
</script>

<style  lang='scss'>
.apiTestAdd{
  &__h{
    height:72px;
    background:rgba(255,255,255,1);
    box-shadow:0px 0px 30px 0px rgba(0,0,0,0.05);
    border-radius:10px;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    &--p{
      font-size:16px;
      font-family:PingFangSC-Medium,PingFang SC;
      font-weight:500;
      margin-left: 30px;
      color:rgba(35,35,42,1);
    }
  }
  &__form{
    display: flex;
    text-align: left;
    flex-direction: column;
    box-shadow:0px 0px 30px 0px rgba(0,0,0,0.05);
    border-radius:10px;
    background: #fff;
    padding-top: 30px;
    &--box{
      display: flex;
      margin-top: 30px;
    }
  }
}
.formItemStyle {
  position: relative;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .ivu-form-item-content{
    width: 100%!important;
  }
  &__box{
    margin-left: -110px;
    position: relative;
  }
}
#formItemStyleWay{
  .ivu-form-item-label{
    width: 200px!important;
  }
}
.star{
  position: absolute;
  color:red;
}
.ivu-btn > span > p{
  color:blue!important;
}
</style>
