<template>
  <page-header-wrapper>
    <Grid :columns="['400px', 1]">
      <a-card title="装备分类管理" class="my-card my-card-has-title" :bordered="false">
        <template #extra>
          <a-button
            type="primary"
            icon="plus"
            shape="circle"
            title="新增"
            @click="handleOpenAddZbflModal(-1)"
          ></a-button>
        </template>
        <a-tree
          :treeData="zbfl.treeData"
          :selectedKeys.sync="zbfl.selectedKeys"
          :expandedKeys.sync="zbfl.expandedKeys"
          @select="(_, event) => handleChangeZbflSelected(event.node.dataRef.data)"
        >
          <template #title="scope">
            <a-dropdown :trigger="['contextmenu']">
              <span>{{ scope.title }}</span>
              <template #overlay>
                <Flex class="contextmenu-zz">
                  <a-button
                    type="text-primary"
                    icon="edit"
                    title="编辑"
                    @click="handleOpenEditZbflModal(scope.dataRef.data)"
                  ></a-button>
                  <a-button
                    type="text-primary"
                    icon="plus"
                    title="新增子项"
                    @click="handleOpenAddZbflModal(scope.key)"
                  ></a-button>
                  <a-button
                    type="text-danger"
                    icon="delete"
                    title="删除"
                    @click="handleDeleteZbfl(scope.key, scope.title)"
                  ></a-button>
                  <a-button
                    type="text-primary"
                    icon="unordered-list"
                    title="详情"
                    @click="handleViewZbfl(scope.key)"
                  ></a-button>
                  <a-button
                    type="text-primary"
                    title="修改军标"
                    style="padding: 0 8px"
                    @click="handleOpenEditZbjbModal(scope.key, scope.dataRef.data)"
                  >
                    <EditIcon size="16px" />
                  </a-button>
                </Flex>
              </template>
            </a-dropdown>
          </template>
        </a-tree>
      </a-card>
      <a-card title="装备管理" class="my-card my-card-has-title" :bordered="false">
        <template #extra>
          <a-button
            v-if="zb.entityType"
            type="primary"
            style="margin-right: 20px"
            @click="handleOpenAddZbModal(record)"
          >
            新增
          </a-button>
          <a-icon type="sync" style="font-size: 30px" @click="$refs['zb-table'].commitAction('query')" />
        </template>
        <AntQueryTable
          ref="zb-table"
          height="100%"
          :queryConfig="zb.queryConfig"
          :showTool="zb.showTool"
          :tableConfig="zb.tableConfig"
        >
          <template #tablecell-action="{ record }">
            <a-button type="text-primary" icon="edit" title="编辑" @click="handleOpenEditZbModal(record)"></a-button>
            <a-button type="text-primary" icon="copy" title="复制" @click="handleOpenCopyZbModal(record)"></a-button>
            <a-popconfirm
              title="确定要删除该装备吗？"
              okText="确定"
              cancelText="取消"
              @confirm="handleDeleteZb(record)"
            >
              <a-button type="text-danger" icon="delete" title="删除"></a-button>
            </a-popconfirm>
          </template>
        </AntQueryTable>
      </a-card>
    </Grid>
    <AntFormModal
      :visible.sync="zbflModal.visible"
      :title="zbflModal.title"
      :formItems="zbflModal.formItems"
      :formRules="zbflModal.formRules"
      :formData="zbflModal.formData"
      :onSubmit="handleSubmitZbfl"
      @success="handleSubmitZbflSuccess"
    ></AntFormModal>
    <a-modal
      v-model="zbflViewModal.visible"
      :title="zbflViewModal.title"
      width="900px"
      :maskClosable="false"
      :destroyOnClose="true"
      :footer="null"
    >
      <a-table
        :dataSource="zbflViewModal.data"
        :columns="[{ dataIndex: 'label', width: 150 }, { dataIndex: 'value' }]"
        :showHeader="false"
        bordered
      >
      </a-table>
    </a-modal>
    <AntFormModal
      :visible.sync="zbjbModal.visible"
      :title="zbjbModal.title"
      :formItems="zbjbModal.formItems"
      :formRules="zbjbModal.formRules"
      :formData="zbjbModal.formData"
      :onSubmit="handleSubmitZbjb"
      @success="handleSubmitZbjbSuccess"
    ></AntFormModal>

    <InfoDataModal
      :visible="AECModal.visible"
      :modalTitle="AECModal.title"
      :opType="AECModal.opType"
      :entityType="zb.entityType"
      :parentId="zb.parentId"
      :dicData="dicData"
      :parentTableRowId="AECModal.opType === 1 ? undefined : AECModal.parentTableRowId"
      @closeModal="handleCLoseAECModal"
    />
  </page-header-wrapper>
</template>

<script>
import InfoDataModal from './modules/infoData.vue'
import EditIcon from './components/EditIcon.vue'
import { postAction } from '@/api/manage'

const listGridInfo = {
  Aircraft: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '类型', dataIndex: 'type' },
    { title: '国家', dataIndex: 'operatorCountry' },
    { title: '军种', dataIndex: 'operatorService' },
    { title: '造价(百万，￥)', dataIndex: 'cost' },
    { title: '服役年', dataIndex: 'yearCommissioned' },
    { title: '退役年', dataIndex: 'yearDecommissioned' },
    { dataIndex: 'action' },
  ],
  Ship: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '类别', dataIndex: 'category' },
    { title: '所属国', dataIndex: 'operatorCountry' },
    { title: '所属军种', dataIndex: 'operatorService' },
    { title: '造价(百万，￥)', dataIndex: 'cost' },
    { title: '服役年', dataIndex: 'yearCommissioned' },
    { title: '退役年', dataIndex: 'yearDecommissioned' },
    { title: '注释', dataIndex: 'comments' },
    { title: '类型', dataIndex: 'type' },
    { dataIndex: 'action' },
  ],
  Submarine: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '类别', dataIndex: 'category' },
    { title: '所属国', dataIndex: 'operatorCountry' },
    { title: '所属军种', dataIndex: 'operatorService' },
    { title: '造价(百万，￥)', dataIndex: 'cost' },
    { title: '服役年', dataIndex: 'yearCommissioned' },
    { title: '退役年', dataIndex: 'yearDecommissioned' },
    { title: '注释', dataIndex: 'comments' },
    { title: '类型', dataIndex: 'type' },
    { dataIndex: 'action' },
  ],
  Weapon: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '生产年代', dataIndex: 'generation' },
    { title: '所属国', dataIndex: 'operatorCountry' },
    { title: '造价(百万，￥)', dataIndex: 'cost' },
    { title: '注释', dataIndex: 'comments' },
    { title: '类型', dataIndex: 'type' },
    { dataIndex: 'action' },
  ],
  Facility: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '类别', dataIndex: 'category' },
    { title: '所属国', dataIndex: 'operatorCountry' },
    { title: '所属军种', dataIndex: 'operatorService' },
    { title: '造价(百万，￥)', dataIndex: 'cost' },
    { title: '服役年', dataIndex: 'yearCommissioned' },
    { title: '退役年', dataIndex: 'yearDecommissioned' },
    { title: '注释', dataIndex: 'comments' },
    { title: '类型', dataIndex: 'type' },
    { dataIndex: 'action' },
  ],
  Satellite: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '类别', dataIndex: 'category' },
    { title: '所属国', dataIndex: 'operatorCountry' },
    { title: '所属军种', dataIndex: 'operatorService' },
    { title: '造价(百万，￥)', dataIndex: 'cost' },
    { title: '服役年', dataIndex: 'yearCommissioned' },
    { title: '退役年', dataIndex: 'yearDecommissioned' },
    { title: '注释', dataIndex: 'comments' },
    { title: '类型', dataIndex: 'type' },
    { dataIndex: 'action' },
  ],
  Comm: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '类型', dataIndex: 'type' },
    { title: '注释', dataIndex: 'comments' },
    { dataIndex: 'action' },
  ],
  Sensor: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '类型', dataIndex: 'type' },
    { title: '注释', dataIndex: 'comments' },
    { title: '最大作用距离（公里）', dataIndex: 'rangeMax' },
    { dataIndex: 'action' },
  ],
  Loadout: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '挂载方案的作用', dataIndex: 'loadoutRole' },
    { title: '注释', dataIndex: 'comments' },
    { dataIndex: 'action' },
  ],
  Magazine: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '装甲', dataIndex: 'armorGeneral' },
    { title: '补给间隔时间（秒）', dataIndex: 'rof' },
    { title: '容量', dataIndex: 'capacity' },
    { title: '注释', dataIndex: 'comments' },
    { dataIndex: 'action' },
  ],
  Mount: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '注释', dataIndex: 'comments' },
    { dataIndex: 'action' },
  ],
  Propulsion: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '类型', dataIndex: 'type' },
    { title: '注释', dataIndex: 'comments' },
    { dataIndex: 'action' },
  ],
  Warhead: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '炸药类型', dataIndex: 'explosivesType' },
    { title: '类型', dataIndex: 'type' },
    { title: '注释', dataIndex: 'comments' },
    { dataIndex: 'action' },
  ],
  Laser: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'name', width: 200, ellipsis: true },
    { title: '类型', dataIndex: 'type' },
    { title: '所属国', dataIndex: 'operatorCountry' },
    { dataIndex: 'action' },
  ],
  hospital: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'resourceName', width: 200, ellipsis: true },
    { title: '经度', dataIndex: 'lng' },
    { title: '纬度', dataIndex: 'lat' },
    { title: '医生数量', dataIndex: 'doctorNum' },
    { title: '护士数量', dataIndex: 'nurseNum' },
    { title: '病床', dataIndex: 'hospitalBed' },
    { dataIndex: 'action' },
  ],
  warehouse: [
    { title: '#DBID', dataIndex: 'id', width: 80 },
    { title: '名称', dataIndex: 'resourceName', width: 200, ellipsis: true },
    { title: '经度', dataIndex: 'lng' },
    { title: '纬度', dataIndex: 'lat' },
    { title: '药材数量', dataIndex: 'medicalNum' },
    { title: '油料', dataIndex: 'fuelNum' },
    { title: '弹药', dataIndex: 'ammunitionNum' },
    { dataIndex: 'action' },
  ],
  Vehicle: [
    { title: '#DBID', dataIndex: 'ID', width: 80 },
    { title: '名称', dataIndex: 'vehicleName', width: 200, ellipsis: true },
    { title: '速度', dataIndex: 'vehicleSpreed' },
    { title: '型号', dataIndex: 'vehicleType' },
    { title: '运油能力', dataIndex: 'fuelAbility' },
    { title: '运药', dataIndex: 'medicalAbility' },
    { title: '运弹药能力', dataIndex: 'ammunitionAbility' },
    { title: '车辆用途', dataIndex: 'vehicleUse' },
    { dataIndex: 'action' },
  ],
}

export default {
  name: 'Zbsjk',
  components: {
    InfoDataModal,
    EditIcon,
  },
  data() {
    return {
      zbfl: {
        treeData: [],
        selectedKeys: [],
        expandedKeys: [],
      },
      zbflModal: {
        visible: false,
        title: '',
        mode: '',
        formItems: [
          {
            label: '上级装备分类',
            prop: 'parentId',
            component: 'AntOriginTreeSelect',
            options: {
              dataSource: () =>
                this.$http({
                  url: '/basedata/entity/getTreeNode',
                  method: 'get',
                }).then((res) => ({ data: [{ key: -1, title: '根级分类' }].concat(res.data) })),
              valueKey: 'key',
            },
          },
          {
            label: '装备分类编码',
            prop: 'entityType',
          },
          {
            label: '装备分类名称',
            prop: 'entityName',
          },
        ],
        formRules: {
          name: [{ required: true, message: '请输入装备分类名称！', trigger: 'blur' }],
        },
        formData: {},
      },
      zbflViewModal: {
        visible: false,
        data: {},
      },
      zbjbModal: {
        visible: false,
        title: '',
        mode: '',
        formItems: [{ label: '军标图片', prop: 'iconId', component: 'IconSelector' }],
        formRules: {},
        formData: {},
      },
      zb: {
        entityType: '',
        parentId: 0,
        queryConfig: {
          items: [
            {
              label: '国家/地区',
              prop: 'operatorCountry',
              component: 'AntOriginSelect',
              options: {
                dataSource: () =>
                  this.$http({
                    url: '/dicdata/operatorcountry/getList',
                    method: 'get',
                  }),
                labelKey: 'description',
                style: {
                  width: '180px',
                },
              },
            },
            { label: '名称', prop: 'name' },
            { label: '#DBID', prop: 'id' },
          ],
        },
        showTool: false,
        tableConfig: {
          query: (params) =>
            this.$http({
              url: '/basedata/' + this.zb.entityType.toLowerCase() + '/getList',
              method: 'post',
              data: { ...params, parentId: this.zb.parentId },
            }),
          columns: [{ dataIndex: 'serial' }, { dataIndex: 'action' }],
          immediate: false,
        },
      },
      AECModal: {
        visible: false,
        title: '',
        opType: 1,
        parentTableRowId: 0,
      },

      // 辅助数据
      dicData: {
        sensorcode: [], //传感器属性
        sensorcapability: [], //传感器能力
        sensorfrequency: [], //传感器频率（雷达照射频率、搜索和跟踪频率）
        dicsignaturetype: [], //信号特征类型
        dicDicDockingFacilitytype: [], //停靠设施类型
        operatorservice: [], // 军种
        satellitecategory: [], //卫星类别
        satellitetype: [], //卫星类型
        operatorcountry: [], // 国家
        dicfacilitycategory: [], // 地面兵力与设施类别
        diccargorytype: [], // 地面兵力与设施类型
        aircraftcode: [], //飞机-属性
        sensorType: [], //传感器-属性
        Shipcode: [], //水面舰艇-属性
        Submarinecode: [], // 潜艇-属性
        dicwarheadcaliber: [], //战斗部口径类型
        warheadtype: [], //战斗部类型
        dicsensorgeneration: [], //技术水平
        loadoutweather: [], //挂载方案使用天气要求
        loadouttimeofday: [], //挂载方案使用时间要求
        loadoutrole: [], //挂载方案的作用
        dicpropulsiontype: [], //推进系统的类型
        dictransfertype: [], //数据传输类型
        dicweapontarget: [], //有效目标
        weaponwra: [], //武器使用规则目标类型
        weaponwraweaponqty: [], //武器使用规则武器齐射数
        weaponwrashooterqty: [], //武器使用规则齐射最大发射单元数
        weaponcode: [], //武器-属性
        weapongeneration: [], //武器所属年代
        loadoutwinchestershotgun: [], //武器状态
        weapontype: [], //武器类型
        weaponwraselfdefencerange: [], //武器防御自防御距离
        dicpropulsionthrottle: [], //油门类型
        dicsubmarinephysicalsize: [], //潜艇停靠设施级别
        dicsubmarinecategory: [], //潜艇类别
        dicsubmarinetype: [], //潜艇类型
        lasertype: [], // 激光类别
        lasercode: [], // 激光属性
        diclasertarget: [], // 激光有效目标
        warheadexplosivestype: [], //炸药类型
        fuel: [], //燃油数据
        aircraftfacilityphysicalsize: [], //物理尺寸级别
        dicMobileunitcategory: [], //移动单位类别
        aircraftfacilitytype: [], //航空保障类型
        dicshipphysicalsize: [], //船舰（水面潜艇）停靠设施级别
        dicshipcargorytype: [], //船舰（水面潜艇）货物_类型
        shipcategory: [], //船舰（水面潜艇）类别
        shiptype: [], //船舰（水面潜艇）类型
        armortype: [], // 装甲级别
        aircraftrunwaylength: [], // 跑道长度
        radiatemodulationmode: [], //辐射源调制方式
        diccommcapability: [], //通信数据链属性
        diccommoperatestatus: [], //通信数据链工作状态
        sensorrole: [], //雷达类别种类
        aircraftcategory: [], // 飞机类别
        aircrafttype: [], // 飞机类型
        aircraftcockpitvisibility: [], // 驾驶员视线等级
        loadoutmissionprofile: [], //默认任务剖面
        dataModelcategory: [], //模型类别
      },
    }
  },
  created() {
    this.getZzTree()
    for (const key in this.dicData) {
      this.$http({
        url: '/dicdata/' + key + '/getList',
        method: 'get',
      }).then((res) => {
        this.dicData[key] = res.data
      })
    }
  },
  methods: {
    async getZzTree() {
      try {
        const res = await this.$http({
          url: '/basedata/entity/getTreeNode',
          method: 'get',
        })
        this.zbfl.treeData = res.data
        this.zbfl.selectedKeys = [this.zbfl.treeData[0].key]
        this.handleChangeZbflSelected(this.zbfl.treeData[0].data)
      } catch (error) {
        console.log(error)
      }
    },
    handleChangeZbflSelected(data) {
      this.zb.entityType = data.entityType
      this.zb.entityName = data.entityName
      this.zb.parentId = data.id
      this.zb.tableConfig.columns = listGridInfo[data.entityType] || []
      this.$refs['zb-table'].commitAction('query')
    },
    handleOpenAddZbflModal(parentId) {
      this.zbflModal.title = '新建装备分类'
      this.zbflModal.mode = 'add'
      this.zbflModal.formData = { parentId, createUserId: localStorage.getItem('userId') }
      this.zbflModal.visible = true
    },
    handleOpenEditZbflModal(data) {
      this.zbflModal.title = '编辑装备分类'
      this.zbflModal.mode = 'edit'
      this.zbflModal.formData = { id: data.id, parentId: data.parentId, entityName: data.entityName,entityType: data.entityType }
      this.zbflModal.visible = true
    },
    handleSubmitZbfl(formData) {
      if (this.zbflModal.mode === 'edit') {
        return this.$http({
          url: '/basedata/entity/editName',
          method: 'get',
          params: formData,
        })
      }
      if (this.zbflModal.mode === 'add') {
        return this.$http({
          url: '/basedata/entity/add',
          method: 'get',
          params: formData,
        })
      }
      return Promise.reject(new Error('未知错误'))
    },
    handleSubmitZbflSuccess() {
      this.getZzTree()
    },
    async handleDeleteZbfl(id, title) {
      try {
        await this.$confirm({ content: `确定删除装备分类-${title}？` })
        await this.$http({
          url: `/basedata/entity/remove`,
          method: 'delete',
          params: { id },
        })
        this.$message.success('删除成功')
        this.getZzTree()
      } catch (error) {
        console.log(error)
      }
    },
    async handleViewZbfl(id) {
      try {
        const res = await this.$http({
          url: '/basedata/entity/getInfo',
          method: 'get',
          params: { id },
        })
        this.zbflViewModal.data = [
          { label: '名称', value: res.data.entityName },
          { label: '备注', value: res.data.remark },
          { label: '创建人', value: res.data.createUserId },
          { label: '创建时间', value: res.data.createTime },
          { label: '类型', value: res.data.entityTypeName },
          { label: '所有子分类个数', value: res.data.childrenCount },
          { label: '包含所有的实体个数', value: res.data.entityCount },
        ]
        this.zbflViewModal.title = res.data.entityName
        this.zbflViewModal.visible = true
      } catch (error) {
        console.log(error)
      }
    },
    handleOpenEditZbjbModal(id, data) {
      this.zbjbModal.title = `修改 ${data.entityName} 军标`
      this.zbjbModal.formData = {}
      this.zbjbModal.formData.id = id
      this.$set(this.zbjbModal.formData, 'iconId', data.iconId)
      this.zbjbModal.visible = true
    },
    handleSubmitZbjb(formData) {
      return postAction('/basedata/entity/setIcon', formData)
    },
    handleSubmitZbjbSuccess() {
      this.getZzTree()
    },
    handleOpenAddZbModal() {
      this.AECModal.opType = 1
      this.AECModal.title = '添加 ' + this.zb.entityName + ' 实体'
      this.AECModal.visible = true
    },
    handleOpenEditZbModal(record) {
      this.AECModal.opType = 3
      this.AECModal.parentTableRowId = record.ID
      console.log('======'+record.ID)
      this.AECModal.title = '编辑 ' + record.name + ' 实体'
      this.AECModal.visible = true
    },
    handleOpenCopyZbModal(record) {
      this.AECModal.opType = 2
      this.AECModal.parentTableRowId = record.id
      this.AECModal.title = '复制 ' + record.name
      this.AECModal.visible = true
    },
    handleCLoseAECModal() {
      this.AECModal.visible = false
      this.AECModal.title = ''
      this.AECModal.opType = 0
      this.$refs['zb-table'].commitAction('query')
    },
    async handleDeleteZb(record) {
      try {
        await this.$http({
          url: '/basedata/' + this.zb.entityType.toLowerCase() + '/remove',
          method: 'delete',
          params: { Guid: record.guid },
        })
        this.$messge.success('删除成功')
        this.$refs['zb-table'].commitAction('query')
      } catch (error) {
        console.log(error)
      }
    },
  },
}
</script>

<style lang="less" scoped></style>
