<template>
  <div class="base-screen-container">
    <div class="form-title_blue" v-if="isShowTitle">{{titleName}}</div>
    <ts-form-item v-if="isShowDsType">
      <ts-radio
        title="类型"
        v-model="selectData.dsType"
        :data="dsTypeSource"
        type="group"
        :isDefaultFirst="true"
        @change="refresh($event,'dsType')"
        :key="selectData.id+'dsType2222'"
      ></ts-radio>
    </ts-form-item>
    <ts-switch
      title="需要权限"
      v-model="selectData.isToken"
      on-label="是"
      off-label="否"
      :key="selectData.id+'isToken2222'"
      @change="refresh($event,'isToken')"
    >
      <tsPopover
        slot="title"
      >注：开启后，请求地址后默认携带token/dep/user/deptcode/deptid/userId/userCode/roleCode/hospCode信息</tsPopover>
    </ts-switch>
    <ts-select
      v-if="selectData.isToken"
      v-model="selectData.tokenParams"
      :source="tokenParamsSource"
      :key="selectData.id+'tokenParams2222'"
      title="权限参数"
      @selected="refresh($event,'tokenParams')"
    ></ts-select>
    <ts-switch
      title="实时推送"
      v-model="selectData.isRealTime"
      on-label="是"
      off-label="否"
      :key="selectData.id+'isRealTime2222'"
      @change="refresh($event)"
    ></ts-switch>
        <ts-switch
      title="单位格式化"
      v-model="selectData.originalTargetUnit"
      on-label="是"
      off-label="否"
      :key="selectData.id+'originalTargetUnit2222'"
      @change="refresh($event)"
    >
    <tsPopover
        slot="title"
      >注：开启后，金额类指标如果做了万元处理，则显示原始数据</tsPopover>
    </ts-switch>
    <ts-form-item v-if="!selectData.dsType||selectData.dsType == '0'">
      <ts-select
        v-model="selectData.dataSourceId"
        :source="dSDataSource"
        :key="selectData.id+'dataSourceId2222'"
        title="数据源"
        @selected="isChangeDSIdBefore?$emit('changeDSIdBefore',$event):refresh($event,'dataSourceId')"
      ></ts-select>
      <ts-form-item
        v-if="isShowResult&&selectData.selectDataSourceResultData &&
                      selectData.selectDataSourceResultData.length > 0"
      >
        <ts-select
          title="结果集"
          :key="'selectDataResult' + selectData.id"
          :source="selectDataSourceResult"
          v-model="selectData.selectDataSourceResult"
          @selected="onSelectColResult($event)"
        ></ts-select>
      </ts-form-item>
    </ts-form-item>
    <template v-if="selectData.dsType == '1'">

      <ts-form-item>
        <ts-select
          title="请求方式"
          v-model="selectData.reqType"
          :key="selectData.id+'reqType'"
          :source="dsReqTypeeSource"
          @change="refresh($event)"
        ></ts-select>
      </ts-form-item>
                <ts-form-item v-if="isShowDsType">
      <ts-radio
        title="接口类型"
        v-model="selectData.apiType"
        :data="apiTypeSource"
        type="group"
        :isDefaultFirst="true"
        @change="refresh($event,'apiType')"
        :key="selectData.id+'apiType'"
      ></ts-radio>
    </ts-form-item>
      <ts-form-item  v-if="selectData.apiType==1">
        <ts-select
        class="apiclass"
          title="通用接口"
          v-model="selectData.reqUrl"
          :key="selectData.id+'reqUrl'"
          :source="apiSource"
          @change="refresh($event)"
        >
        </ts-select>
        <div  class="testclass">
            <ts-button
              style="margin-left:5px"
              @click="isOnTestBefore?$emit('testBeforeEvent',$event):testURL()"
            >{{testText}}</ts-button>
          </div>
     </ts-form-item>
      <ts-form-item v-if="selectData.apiType!=1" >
        <ts-textarea
          title="请求地址"
          v-model="selectData.reqUrl"
          @change="refresh($event)"
          height="100px"
        >
          <div slot="after">
            <ts-button
              style="margin-left:5px"
              @click="isOnTestBefore?$emit('testBeforeEvent',$event):testURL()"
            >{{testText}}</ts-button>
          </div>
        </ts-textarea>
      </ts-form-item>
      <!-- <ts-form-item style="margin-bottom:5px">
        <ts-textarea
          title="内容类型"
          v-model="selectData.contentType"
          @change="refresh($event)"
          height="35px"
        >
          <tsPopover slot="title">默认为:application/x-www-form-urlencoded; charset=utf-8</tsPopover>
        </ts-textarea>
      </ts-form-item>-->
      <ts-form-item style="margin-bottom:5px">
        <ts-select
          title="内容类型"
          v-model="selectData.contentType"
          @selected="refresh($event)"
          :source="contentTypeSource"
          :key="'contentType'+selectData.id"
        ></ts-select>
      </ts-form-item>
      <ts-form-item>
        <ts-input title="返回节点" v-model="selectData.resNode" @change="refresh($event)">
          <tsPopover slot="title">
            【返回节点】为取值节点，数据取到对应的哪一层，
            <br />如Object或rows等
          </tsPopover>
        </ts-input>
      </ts-form-item>
      <!-- 所属指标列表 -->
      <!-- <ts-form-item>
        <ts-select
          v-model="selectData.targetCode"
          @selected="refresh"
          title="所属指标"
          :source="targetSource"
          :key="'targetCode'+selectData.id"
        />
      </ts-form-item>-->
      <!-- 所属指标树形 -->
      <ts-form-item>
        <tsTargetSelect
          v-model="selectData.targetCode"
          title="所属指标"
          :source="targetSelectSource"
          :key="'targetCode'+selectData.id"
          @change="refresh($event,'target')"
        ></tsTargetSelect>
        <!-- <ts-select
          v-model="selectData.targetCode"
          @change="refresh($event,'target')"
          title="所属指标"
          :source="targetSourceTree"
          :key="'targetCode'+selectData.id"
        />-->
      </ts-form-item>
      <template v-if="selectData.targetCode">
        <ts-form-item>
          <ts-radio
            title="排序方式"
            v-model="selectData.sortOrder"
            :data="sortOrderSource"
            type="group"
            :isDefaultFirst="true"
            @change="refresh($event,'sortOrder')"
          ></ts-radio>
        </ts-form-item>
        <ts-form-item>
          <ts-select
            v-model="selectData.sortName"
            @change="refresh($event,'sortName')"
            title="排序列"
            :source="sortNameSource"
            :key="'sortName'+selectData.id"
          >
            <tsPopover slot="title">未选时，将默认为第一个指标的第一列;只针对行转列接口有效；</tsPopover>
          </ts-select>
        </ts-form-item>
        <ts-form-item>
          <ts-select
            v-model="selectData.pivotType"
            @change="refresh($event,'pivotType')"
            title="维度"
            :source="weiduSource"
            :key="'weidu'+selectData.id"
          >
            <tsPopover slot="title">选中维度，则进行行转列显示</tsPopover>
          </ts-select>
        </ts-form-item>
        <ts-row type="flex">
          <ts-col :flex="1">
            <ts-form-item>
              <ts-switch
                title="是否占比"
                v-model="selectData.generalType"
                on-label="是"
                off-label="否"
                on-value="proportion"
                off-value
                @change="refresh($event)"
              >
                <tsPopover slot="title">注：开启并解析后，出参将有占比信息</tsPopover>
              </ts-switch>
            </ts-form-item>
          </ts-col>
          <ts-col :flex="1">
            <ts-form-item>
              <ts-switch
                title="启用别名"
                v-model="selectData.enableBusiCodeAlias"
                on-label="是"
                off-label="否"
                @change="refresh($event)"
              > <tsPopover slot="title">注：开启后，将显示指标别名</tsPopover></ts-switch>
            </ts-form-item>
          </ts-col>
        </ts-row>
      </template>
    </template>
  </div>
</template>

<script>
import biUtils from '../../utils/biUtils'
import tsTargetSelect from '../uiElement/tsTargetSelect'
export default {
  name: 'attrDataSource',
  components: { tsTargetSelect },
  props: {
    isChangeDSIdBefore: {
      // 是否在改版数据源之前调用
      type: Boolean,
      default: false
    },
    titleName: {
      type: String,
      default: '数据源配置'
    },
    isShowResult: {
      // 是否显示结果集
      type: Boolean,
      default: false
    },
    isShowDsType: {
      // 是否显示数据源类型
      type: Boolean,
      default: true
    },
    isShowTitle: {
      type: Boolean, // 是否显示标题
      default: true
    },
    testText: {
      type: String,
      default: '解析'
    },
    isOnTestBefore: {
      // 是否解析之前触发，运用解析之前的询问或操作等
      type: Boolean,
      default: false
    },
    isOtherSelectData: {
      // 是否选中对象
      type: Boolean,
      default: false
    },
    otherSelectData: {
      // 其他选中的对象
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      selectData: this.isOtherSelectData
        ? this.otherSelectData || {}
        : JSON.parse(JSON.stringify(this.$store.state.bi.selectData)),
      dsTypeSource: [
        { value: '0', text: '自定义服务' },
        { value: '1', text: 'URL' }
      ],
      apiTypeSource:[
         { value: '0', text: '自定义' },
         { value: '1', text: '通用' }
        ],
      weiduSource: {
        dataType: 'local',
        code: 'value',
        text: 'label',
        data: [
          { value: 'dept', label: '科室' },
          { value: 'doctor', label: '医生' },
          { value: 'yqdm', label: '院区' },
          { value: 'item', label: '项目' }
        ],
        isReq: true,
        value: {
          name: '',
          code: ''
        }
      },
      // 需要权限可选字段
      tokenParamsSource: {
        dataType: 'local',
        code: 'value',
        text: 'value',
        data: [
          { value: 'token' },
          { value: 'deptcode' },
          { value: 'deptid' },
          { value: 'userId' },
          { value: 'userCode' },
          { value: 'roleCode' },
          { value: 'hospCode' },
          { value: 'corpCode' },
          { value: 'orgRang' }
        ],
        choice: true
      },
      sortOrderSource: [
        { value: '', text: '默认' },
        { value: 'asc', text: '升序' },
        { value: 'desc', text: '降序' }
      ],
      apiSource: {
        dataType: 'local',
        code: 'itemCode',
        text: 'itemName',
        data: [],
        isReq: true,
        value: {
          name: '',
          code: ''
        }
      },
      dsReqTypeeSource: {
        dataType: 'local',
        code: 'value',
        text: 'label',
        data: [
          { value: 'get', label: 'get' },
          { value: 'post', label: 'post' }
        ],
        isReq: true,
        value: {
          name: '',
          code: ''
        }
      },
      contentTypeSource: {
        dataType: 'local',
        code: 'value',
        text: 'label',
        isReq: true,
        data: [
          { value: 'application/json', label: 'application/json' },
          {
            value: 'application/x-www-form-urlencoded',
            label: 'application/x-www-form-urlencoded'
          }
        ]
      },
      targetSelectSource: {
        dataType: 'local',
        data: this.$store.state.bi.targetSource,
        choice: true
      },
      // 数据源
      dSDataSource: {
        dataType: 'local',
        code: 'id',
        data: this.$store.state.bi.dataSource,
        text: 'queryName',
        condition: 'condition',
        isReq: true,
        value: {
          name: '',
          code: ''
        }
      }
    }
  },
  computed: {
    // 下拉数据源-值
    selectDataSourceCode() {
      return biUtils.dataSourceColSource(
        this.selectData.selectDataSourceData[0]
      )
    },
    // 下拉数据源-值
    selectDataSourceResult() {
      return biUtils.dataSourceColSource(
        this.selectData.selectDataSourceResultData
      )
    },
    // 下拉数据源-值
    sortNameSource() {
      let data = this.selectData.targetCode
        ? this.selectData.targetCode.split(',')
        : []
      if (data && data.length > 0) {
        data = data.map(res => {
          return { name: res }
        })
      }
      return biUtils.dataSourceColSource(data)
    }
  },
  mounted() {
    this.selectData = this.isOtherSelectData
      ? this.otherSelectData
      : JSON.parse(JSON.stringify(this.$store.state.bi.selectData))
  },
  created() {
    this.getUrlList()
  },
  methods: {
    // // 数据源参数
    // dataSourceColSource(data) {
    //   return {
    //     dataType: 'local',
    //     code: 'name',
    //     text: 'name',
    //     data: data || [],
    //     isReq: true,
    //     value: {
    //       name: '',
    //       code: ''
    //     }
    //   }
    // },
    // 测试URL，获取字段下拉
    testURL() {
      const _this = this
      if (!this.selectData.reqUrl) {
        this.$utils.msg(this, 'url不可为空！', 'warning')
        return
      }
      let url = this.selectData.reqUrl
      _this.selectData.selectDataSourceCodeOption = []
      let data = this.selectData.isToken
        ? biUtils.setToken({}, this.selectData, this, global)
        : {}
      if (_this.selectData.targetCode) {
        // 存在所属指标，入参加内容
        data.busiCode = _this.selectData.targetCode //'80010' //
        // data.busiDate = '2020-04'
        data.beginDate = this.$utils.getTodayDate()
        data.model = true
        data.endDate = this.$utils.getTodayDate()
        if (_this.selectData.pivotType) {
          data.pivotType = _this.selectData.pivotType
        }
        if (_this.selectData.generalType) {
          data.generalType = _this.selectData.generalType
        }
        data.enableBusiCodeAlias = _this.selectData.enableBusiCodeAlias || false
      }
      this.$api({
        url: url,
        data: data,
        method: this.selectData.reqType || 'get',
        headers: {
          'Content-Type':
            (this.selectData.contentType ||
              'application/x-www-form-urlencoded') + '; charset=utf-8'
        }
      })
        .then(function(response) {
          let dataObject = response
          if (_this.selectData.resNode) {
            // 取节点
            for (let node of _this.selectData.resNode.split('.')) {
              dataObject = dataObject[node]
            }
          } else {
            dataObject = response.rows || response.object || []
          }
          if (Array.isArray(dataObject)) {
            dataObject = dataObject[0]
          }
          _this.$utils.msg(_this, '解析成功', 'success')
          if (dataObject) {
            for (let item of Object.keys(dataObject)) {
              _this.selectData.selectDataSourceCodeOption.push({ name: item })
            }
          }
          _this.setStoreArr()
          _this.$nextTick(() => {
            _this.$emit('changedDSId') //改变数据源之后
          })
        })
        .catch(function(error) {
          console.warn(error)
          _this.$utils.msg(_this, error.message || '解析失败', 'error')
        })
    },
    //获取字典url
    getUrlList(){
     let  _this = this
      this.$api({
        url:'/ts-system/api/dict/item/list?pageSize=100&dictTypeId=612c4f12a31d82633c8f5db1',
        method:'get'
      }).then(res=>{
        _this.apiSource.data = res.rows
      })
    },
    refresh(ev, key, item) {
      this.$nextTick(() => {
        switch (key) {
          case 'dsType':
            if (this.selectData.dsType == '1' && !this.selectData.reqType) {
              this.selectData.reqType = 'get'
              this.selectData.contentType = 'application/json'
            }
            break
          case 'dataSourceId': // 下拉数据源
            this.selectData.dataSourceId = ev.id
            this.selectData.dataSourceName = ev.queryName
            if (
              this.selectData.dataSourceData &&
              this.selectData.dataSourceData.length > 0 //处理存在有子选项的清空，如门户
            ) {
              this.selectData.dataSourceData.forEach(res => {
                res.selectDataSourceCode = ''
                res.selectDataSourceResult = ''
              }) //清空字段名
            }
            //清空结果集和字段
            this.selectData.selectDataSourceData = []
            this.selectData.selectDataSourceResultData = []
            if (this.selectData.selectDataSourceResult) {
              this.selectData.selectDataSourceResult = ''
            }
            this.selectData.selectDataSourceCode = ''
            if (ev.serviceType == '2') {
              // 结果集
              if (ev.columnDefine) {
                for (let item of JSON.parse(ev.columnDefine)) {
                  this.selectData.selectDataSourceResultData.push({
                    name: item.name,
                    tableColumns: item.tableColumns
                  })
                }
              }

              // for (let res of this.selectData.dataSourceData) {
              this.selectData.selectDataSourceCodeOption = []
              // }
            } else {
              if (ev.columnDefine) {
                for (let item of JSON.parse(ev.columnDefine)) {
                  this.selectData.selectDataSourceData.push({
                    name: item.name
                  })
                }
              }
              // for (let res of this.selectData.dataSourceData) {
              this.selectData.selectDataSourceCodeOption = this.selectData.selectDataSourceData
              // }
            }
            if (ev.conditionDefine) {
              this.selectData.selectDataSourceParams = JSON.parse(
                ev.conditionDefine
              )
            }

            break
        }
        this.setStoreArr()
        this.$nextTick(() => {
          this.$emit('changedDSId') //改变数据源之后
        })
      })
    },
    // 监听数据源字段
    onSelectColResult(ev) {
      this.$nextTick(() => {
        this.selectData.selectDataSourceData = []
        this.selectData.selectDataSourceCodeOption = []
        for (let items of ev.tableColumns) {
          this.selectData.selectDataSourceCodeOption.push({
            name: items.name
          })
        }
        this.setStoreArr()
        this.$nextTick(() => {
          this.$emit('changedDSResult') //改变数据源之后
        })
      })
    },
    setStoreArr() {
      if (this.isOtherSelectData) {
        this.$emit('setStoreArr', this.otherSelectData) //改变数据源之后
      } else {
        // 非选择器
        this.$store.commit('setSelectData', { ...this.selectData })
        this.$store.commit('saveArr', { data: { ...this.selectData } })
        this.$store.commit('setNatureArr', { ...this.$store.state.bi.natureArr })
      }
    }
  },
  watch: {
    '$store.state.bi.selectData': {
      handler(val) {
        this.selectData = this.isOtherSelectData
          ? this.otherSelectData || {}
          : JSON.parse(JSON.stringify(this.$store.state.bi.selectData))
        if (
          this.selectData.isToken &&
          typeof this.selectData.tokenParams == 'undefined'
        ) {
          // 需要权限默认选中全部
          if (!this.selectData.dsType || this.selectData.dsType == '0') {
            this.selectData.tokenParams =
              'token,deptcode,deptid,userId,userCode,roleCode,hospCode,corpCode,orgRang'
          } else {
            this.selectData.tokenParams =
              'token,deptcode,deptid,userId,userCode,roleCode,hospCode,corpCode'
          }
        }
      },
      deep: true
    },
    otherSelectData: {
      handler(val) {
        this.selectData = this.isOtherSelectData
          ? this.otherSelectData || {}
          : JSON.parse(JSON.stringify(this.$store.state.bi.selectData))
      },
      deep: true
    },
    '$store.state.bi.dataSource': {
      handler(val) {
        // 数据源
        this.dSDataSource = {
          dataType: 'local',
          code: 'id',
          data: val,
          text: 'queryName',
          condition: 'condition',
          isReq: true,
          value: {
            name: '',
            code: ''
          }
        }
      },
      deep: true
    }
  }
}
</script>
<style lang="less" scoped>
.apiclass{
  width:calc(100% - 38px) !important;
  float:left;
}
.testclass{
  width: 38px;
  float: left;
}
</style>
