<template>
  <view class="p-20rpx h-full overflow-hidden flex flex-col">
    <view class="flex-1 relative">
      <view class="absolute top-0 left-0 w-full h-full">
        <scroll-view scroll-y="true" class="h-full">
          <u-form ref="uForm" class="cu-form" label-width="200">
            <u-form-item
              v-for="(item, i) in template"
              :key="i"
              :label="item.name"
            >
              <template v-if="!item.isMore">
                <view class="flex items-center flex-1">
                  <template v-if="item.component == 'InputTextArea'">
                    <u-input
                      border
                      class="flex-1"
                      type="textarea"
                      v-model="item.value"
                      :suffix="item.unit"
                      placeholder="请输入"
                    />
                  </template>
                  <template v-else>
                    <u-input
                      border
                      :disabled="item.readonly"
                      class="w-full"
                      v-model="item.value"
                      :suffix="item.unit"
                      placeholder="请输入"
                    />
                  </template>
                </view>
              </template>
              <template v-else>
                <view class="w-full">
                  <view
                    class="w-full flex my-10rpx"
                    v-for="(arr, j) in item.value"
                    :key="j"
                  >
                    <view class="w-140rpx mr-20rpx">
                      <u-input
                        type="number"
                        :clearable="false"
                        border
                        v-model="arr.year"
                        placeholder="请输入"
                      />
                    </view>
                    <view class="flex-1 flex items-center">
                      <u-input
                        type="number"
                        :clearable="false"
                        border
                        v-model="arr.value"
                        placeholder="请输入"
                      />
                      <!-- <view class="opacity-50 ml-10rpx">{{ item.unit }}</view> -->
                    </view>
                    <view
                      @click="addDomain(item)"
                      v-if="j == 0"
                      class="px-10rpx"
                    >
                      <u-icon name="plus" size="34"></u-icon>
                    </view>
                    <view
                      @click="removeDomain(item, j)"
                      class="px-10rpx"
                      v-else
                    >
                      <u-icon name="minus" size="34"></u-icon>
                    </view>
                  </view>
                </view>
              </template>
            </u-form-item>
          </u-form>
        </scroll-view>
      </view>
    </view>
    <view class="grid grid-cols-2 gap-x-20rpx">
      <u-button class="mt-20rpx" round @click="handleCancel"> 取消 </u-button>
      <u-button class="mt-20rpx" type="primary" round @click="handleSubmit">
        保存
      </u-button>
    </view>
  </view>
</template>
<script>
const defaultData = {
  chart_nongye: {
    label: '统计数据-农业',
    unit: '万元',
  },
  chart_yuye: {
    label: '统计数据-渔业',
    unit: '万元',
  },
  chart_xumuye: {
    label: '统计数据-畜牧业',
    unit: '万元',
  },
  chart_lingye: {
    label: '统计数据-林业',
    unit: '万元',
  },
  chart_activity: {
    label: '统计数据-其他',
    unit: '万元',
  },
}

import { concat, cloneDeep, template } from 'lodash-es'
const formList = [
  {
    field: 'id',
    label: '街镇ID',
    required: false,
    component: 'Input',
    readonly: true,
  },
  {
    field: 'name',
    label: '街镇名称',
    required: true,
    component: 'Input',
  },
  {
    field: 'address',
    label: '街镇地址',
    required: true,
    component: 'Input',
  },
  {
    field: 'areas',
    label: '街镇面积',
    required: true,
    component: 'Input',
  },
  {
    field: 'cultivated',
    label: '耕地面积',
    required: true,
    component: 'Input',
  },
  {
    field: 'workforce',
    label: '街镇人数',
    required: true,
    component: 'Input',
  },
  {
    field: 'description',
    label: '街镇介绍',
    required: false,
    component: 'InputTextArea',
  },
]
export default {
  props: {
    data: {
      type: Object,
      default: () => {},
    },
  },
  computed: {
    isEdit() {
      return !!this.data
    },
  },
  data() {
    return {
      template: [],
      form: {
        id: '',
        name: '',
        address: '',
        areas: '',
        cultivated: '',
        workforce: '',
        description: '',
        extends: '',
      },
    }
  },
  methods: {
    isObject(val) {
      return Object.prototype.toString.call(val) === '[object Object]'
    },
    isArray(val) {
      return Object.prototype.toString.call(val) === '[object Array]'
    },
    addDomain(item) {
      item.value.push({
        value: '',
        year: '',
      })
    },
    removeDomain(item, index) {
      item.value.splice(index, 1)
    },
    handleCancel() {
      this.$emit('cancel')
    },
    async handleSubmit() {
      const params = {}
      this.template.forEach((e) => {
        if (e.isMore) {
          const temp = {}
          e.value.forEach((el) => {
            if (el.year) temp[el.year] = el.value
          })
          if (!params.extends) params.extends = {}
          params['extends'][e.slug] = temp
        } else {
          params[e.slug] = e.value
        }
      })

      await this.citydataEdit(params)
      this.$emit('confirm')
    },
    async citydataEdit(params) {
      try {
        await this.$http.put(`api/agricultural-basic/${params.id}`, {
          ...params,
          type: 2,
        })
        this.$u.toast('修改成功')
      } catch ({ data }) {
        this.$u.toast(data.message)
      }
    },
    isObject(val) {
      return Object.prototype.toString.call(val) === '[object Object]'
    },
    isArray(val) {
      return Object.prototype.toString.call(val) === '[object Array]'
    },
  },
  watch: {
    data: {
      handler(val) {
        const data = val ?? {}
        const defaultObj = {}
        Object.keys(defaultData).forEach((item) => {
          defaultObj[item] = data.extends[item] ?? {}
        })

        const tempData = Object.keys(defaultObj).reduce((pre, cur) => {
          const currentData = defaultData[cur]
          const obj = {
            name: currentData.label,
            unit: currentData.unit,
            slug: cur,
          }
          const extend = defaultObj[cur]
          if (this.isObject(extend) || this.isArray(extend)) {
            const temp = []

            if (Object.keys(extend).length === 0) {
              temp.push({
                value: '',
                year: null,
              })
            }

            for (const key in extend) {
              temp.push({
                value: extend[key],
                year: key,
              })
            }

            return concat(pre, {
              ...obj,
              isMore: true,
              value: temp,
            })
          }
        }, [])

        const extendsData = formList.reduce((pre, cur) => {
          const currentData = data[cur.field]
          const obj = {
            isMore: false,
            name: cur.label,
            slug: cur.field,
            value: currentData,
            readonly: cur.readonly,
            component: cur.component,
          }
          return pre.concat([obj])
        }, [])
        this.template = extendsData.concat(tempData)
      },
      immediate: true,
      deep: true,
    },
  },
}
</script>
