import SaveForm from '@/components/save-form'
import Pagination from '@/components/pagination'
import {
  NButton,
  NCascader,
  NDataTable,
  NDescriptions,
  NDescriptionsItem,
  NFormItem,
  NInput,
  NModal,
  NSpace,
  NTreeSelect
} from 'naive-ui'
import type { TreeSelectOption } from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import CityOperation from '../modal/city-operation'
import { cityFeeSettingPage, sysAreaPage, sysAreaDetailCode, queryAllProvince } from '../api'
import numeral from 'numeral'
export default defineComponent({
  name: 'city-list',
  setup() {
    const state = reactive({
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 0
      },
      searchForm: {
        cityCode: ''
      },
      dataList: [] as any,
      visiableCity: false,
      cityType: 'add',
      cityData: {} as any,
      areaList: [] as any
    })

    const columns = () => {
      return [
        {
          title: '城市信息',
          key: 'id',
          render(row: any) {
            return (
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="城市名称">{row.cityName}</NDescriptionsItem>
                <NDescriptionsItem label="城市编号">{row.id}</NDescriptionsItem>
                {/* <NDescriptionsItem label="补助标准">
                  {row.orchestraSubsidyStandardName}
                </NDescriptionsItem> */}
              </NDescriptions>
            )
          }
        },

        {
          title: '团练宝零售价',
          key: 'vipPrice',
          render(row: any) {
            return (
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="团练宝零售价">
                  {numeral(row.vipPrice).format('0,0.00')}元/6个月
                </NDescriptionsItem>
                <NDescriptionsItem label="团练宝团购价">
                  {' '}
                  {numeral(row.vipGroupPrice).format('0,0.00')}元/6个月
                </NDescriptionsItem>
                <NDescriptionsItem label="团练宝原价">
                  {' '}
                  {numeral(row.vipOriginalPrice).format('0,0.00')}元/6个月
                </NDescriptionsItem>
              </NDescriptions>
            )
          }
          // render(row: any) {
          //   return `${numeral(row.vipPrice).format('0,0.00')}元/6个月`
          // }
        },
        // {
        //   title: '团练宝团购价',
        //   key: 'vipGroupPrice',
        //   render(row: any) {
        //     return `${numeral(row.vipGroupPrice).format('0,0.00')}元/6个月`
        //   }
        // },
        // {
        //   title: '团练宝原价',
        //   key: 'vipOriginalPrice',
        //   render(row: any) {
        //     return `${numeral(row.vipOriginalPrice).format('0,0.00')}元/6个月`
        //   }
        // },
        // {
        //   title: '补助标准',
        //   key: 'orchestraSubsidyStandardName'
        // },
        {
          title: '更新人',
          key: 'operatorName',
          render(row: any) {
            return (
              <NDescriptions labelPlacement="left" column={1}>
                <NDescriptionsItem label="更新人">{row.operatorName}</NDescriptionsItem>
                <NDescriptionsItem label="更新时间">{row.updateTime}</NDescriptionsItem>
              </NDescriptions>
            )
          }
        },
        // {
        //   title: '更新时间',
        //   key: 'updateTime'
        // },
        {
          title: '操作',
          key: 'operation',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  size="small"
                  text
                  //v-auth="cityFeeSetting/update1597887290159779842"
                  onClick={() => {
                    state.visiableCity = true
                    state.cityType = 'edit'
                    state.cityData = row
                  }}
                >
                  修改
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

    const saveForm = ref()
    const onSubmit = () => {
      state.pagination.page = 1
      getList()
    }

    const onSearch = () => {
      saveForm.value?.submit()
    }
    const onBtnReset = () => {
      saveForm.value?.reset()
    }

    const getList = async () => {
      try {
        state.loading = true
        const { data } = await cityFeeSettingPage({ ...state.pagination, ...state.searchForm })
        state.loading = false
        state.pagination.pageTotal = Number(data.total)
        state.dataList = data.rows || []
      } catch {
        state.loading = false
      }
    }

    // 获取所在城市
    const getAreaAll = async () => {
      try {
        const { data } = await queryAllProvince()
        ;(data || []).forEach((child: any) => {
          child.isLeaf = false
          child.areas.forEach((city: any) => {
            city.isLeaf = true
            city.areas = null
          })
        })
        state.areaList = data
      } catch {}
    }

    // 加载列表
    const handleLoad = async (option: TreeSelectOption) => {
      try {
        const res = await sysAreaPage({
          page: 1,
          rows: 999,
          parentId: option.id
        })
        const data = res.data.rows || []

        const tempList = [] as any
        data.forEach((item: any) => {
          tempList.push({ key: item.code, label: item.name, id: item.id, isLeaf: true })
        })
        option.children = tempList
      } catch {
        //
      }
    }

    onMounted(async () => {
      getAreaAll()
      getList()

      if (state.searchForm.cityCode) {
        try {
          const codeDetail = await sysAreaDetailCode(state.searchForm.cityCode)

          const res = await sysAreaPage({
            page: 1,
            rows: 999,
            parentId: codeDetail.data.parentOrganId
          })
          const data = res.data.rows || []

          const tempList = [] as any
          data.forEach((item: any) => {
            tempList.push({ key: item.code, label: item.name, id: item.id, isLeaf: true })
          })

          state.areaList.forEach((area: any) => {
            if (area.id === codeDetail.data.parentOrganId) {
              area.children = tempList
            }
          })
        } catch {
          //
        }
      }
    })

    return () => (
      <>
        <SaveForm
          ref={saveForm}
          model={state.searchForm}
          onSubmit={onSubmit}
          onSetModel={(val: any) => (state.searchForm = val)}
        >
          <NFormItem path="cityCode">
            <NCascader
              placeholder="请选择城市"
              v-model:value={state.searchForm.cityCode}
              options={state.areaList}
              checkStrategy="child"
              childrenField="areas"
              expandTrigger="hover"
              valueField="code"
              labelField="name"
              clearable
              filterable
            />
          </NFormItem>
          <NFormItem>
            <NSpace>
              <NButton type="primary" onClick={onSearch}>
                搜索
              </NButton>
              <NButton type="default" onClick={onBtnReset}>
                重置
              </NButton>
            </NSpace>
          </NFormItem>
        </SaveForm>

        <NSpace style={{ paddingBottom: '12px' }}>
          <NButton
            type="primary"
            //v-auth="cityFeeSetting/save1597887194890358786"
            onClick={() => {
              state.visiableCity = true
              state.cityType = 'add'
              state.cityData = {}
            }}
          >
            添加城市
          </NButton>
        </NSpace>
        <NDataTable loading={state.loading} columns={columns()} data={state.dataList}></NDataTable>
        <Pagination
          v-model:page={state.pagination.page}
          v-model:pageSize={state.pagination.rows}
          v-model:pageTotal={state.pagination.pageTotal}
          onList={getList}
          sync
          saveKey="city-list"
        ></Pagination>

        <NModal
          v-model:show={state.visiableCity}
          preset="dialog"
          showIcon={false}
          title={state.cityType === 'add' ? '添加城市' : '修改城市'}
          style={{ width: '500px' }}
        >
          <CityOperation
            type={state.cityType}
            data={state.cityData}
            areaList={state.areaList}
            onGetList={getList}
            onClose={() => (state.visiableCity = false)}
          />
        </NModal>
      </>
    )
  }
})
