<template>
  <div class="bigBox">
    <section v-show='props.isShowTotal' ref="getHeight">
      <ScsbTotal :obj="fromObj" ref="aqqcTotal" :key="keys" />
    </section>
    <!-- 查询 -->
    <el-divider />
    <MOSTY.Search :searchArr="searchArr" ref="resetFormRef" @submit="onSearch" />
    <el-divider />
    <div class='tabox'>
      <section class="button">
        <el-button @click="addUserHander" v-if='isAuth && props.obj.saveBtnShow'>
          <el-icon>
            <Plus />
          </el-icon>新增</el-button>
        <MOSTY.ExportExcel :exportSheets="exportSheets" :exportInfo="exportInfo" @getSheets="getSheets"
          :ditData="{ D_BZ_SYZT, D_TB_JCYWLX }" />
        <el-button @click="handleewm" v-loading="exportLoadings" :disabled="pageData.tableData.length == 0"
          class="ml10">
          <el-icon>
            <Download />
          </el-icon>批量导出二维码</el-button>
      </section>
      <section :style="{ 'height': totalHeight }">
        <MOSTY.Table :table-columns="pageData.tableColumns" :tableData="pageData.tableData" :tableloading="tableloading"
          :isSelect="true" :isSort="true" @handleSelecTable="handleSelecTable">
          <template #sign="{ row }">
            <p style=" width: 12px; height: 12px;border-radius: 50%;margin: 0 auto"
              :style="{ 'background-color': row?.sign ? '#33CC00' : '#FC5F76' }"></p>
          </template>
          <template #sblx="{ row }">
            <dict-tag v-if="row.sblx" :options="D_TB_JCYWLX" :value="row.sblx" :tag="false" />
            <span v-else>无</span>
          </template>
          <template #sitename="{ row }">
            <span>{{ row.sitename ? row.sitename : '' }}{{ row.buildingname ? '-' + row.buildingname : '' }}{{
              row.floorname ? '-' + row.floorname : '' }}{{ row.partname ? '-' + row.partname : '' }}</span>
          </template>
          <template #jdqk="{ row }">
            <dict-tag v-if="row.jdqk" :options="D_BZ_SF" :value="row.jdqk" :tag="false" />
            <span v-else>无</span>
          </template>
          <template #responsibilitypersonname="{ row }">
            <span>{{ row.responsibilitypersonname ? row.responsibilitypersonname.replace(/（null）/g, '') : '' }}</span>
          </template>
          <template #state="{ row }">
            <dict-tag v-if="row.state" :options="D_BZ_SYZT" :value="row.state" :tag="false"
              :color="row.state == '01' ? 'green' : 'red'" />
            <span v-else>无</span>
          </template>
          <template #actions="{ row }">
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="复制该条数据并进行数据编辑?"
              @confirm="handlcopy(row)" v-if='isAuth && props.obj.saveBtnShow'>
              <template #reference>
                <span class="operecopy" size="small">
                  <el-icon>
                    <CopyDocument />
                  </el-icon>
                  复制</span>
              </template>
            </el-popconfirm>
            <span class="operedit" @click="handlexg(row)" v-if='isAuth && props.obj.saveBtnShow'>
              <el-icon>
                <EditPen />
              </el-icon>编辑</span>
            <el-popconfirm v-if='isAuth && props.obj.saveBtnShow' confirm-button-text="是" cancel-button-text="否"
              icon-color="red" title="确定要删除?" @confirm="handledelete(row)">
              <template #reference>
                <span class="operdel" size="small">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除</span>
              </template>
            </el-popconfirm>
            <span class="operesee" @click="handleSee(row)">
              <el-icon>
                <View />
              </el-icon>查看</span>
          </template>
        </MOSTY.Table>
      </section>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="pageData.listQuery" @changeNo="handleCurrentChange"
          @changeSize="handleSizeChange" />
      </div>
    </div>
  </div>
  <!--生产设备设施-->
  <div v-if="addtzsbShow" class="dialog-box">
    <Addscsbssindex :formData="formData" @changePage="changePage" :type="props.obj.type" @createPage="createPage" />
  </div>
</template>
<script setup>
import * as MOSTY from "@/components/MyComponents/index";
import Addscsbssindex from "@/components/dialog/Addscsbssindex.vue";
import ScsbTotal from '@/views/yxkzgl/sbss/scsbss/ScsbTotal.vue'
import { reactive, ref, onMounted, watch, getCurrentInstance, nextTick } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { getAuth, downloadewm } from "@/utils/tools.js";
import { ElMessage } from "element-plus";
import Produce from "./Produce.js"
import { useStore } from "vuex"
import { singleObjectCheck } from "@/utils/tools.js"

const store = useStore()
const { proxy } = getCurrentInstance();
const { D_TB_JCYWLX, D_BZ_SYZT, D_BZ_SF } = proxy.$dict("D_TB_JCYWLX", "D_BZ_SYZT", "D_BZ_SF");
const emits = defineEmits(["handleChange", 'searchChange']);
const exportLoadings = ref(false)
const props = defineProps({
  obj: {
    default: null,
    type: Object
  },
  type: {
    default: '',
    type: String
  },
  title: {
    default: '',
    type: String
  },
  tableHeight: {
    default: '40vh',
    type: String
  },
  isShowTotal: {
    type: Boolean,
    default: false
  }
});
//end
const showadd = ref(true)
const tableloading = ref(false);
const formData = ref({
  title: "",
  saveBtnShow: true,
});
let resetFormRef = ref()
const addtzsbShow = ref(false)
// 打叶风分设备
let bladeBlowingEquipment = [
  'sblx',
  'name',
  'jdqk',
  'usertime',
  'sitename',
  'buildingname',
  // 'floorname',
  'partname',
  'location',
  'responsibilitydeptname',
  'responsibilitypersonname'
]
// 工业梯台  工业梯台
let industrialLadder = [
  'sblx',
  'name',
  'landingType',
  'usertime',
  'sitename',
  'buildingname',
  // 'floorname',
  'partname',
  'location',
  'responsibilitydeptname',
  'responsibilitypersonname'
]
const pageData = reactive({
  listQuery: {
    type: '1',
    keywords: '',
    siteName: '',
    sblx: '',
    pageSize: 10,
    pageCurrent: 1,
    total: 0
  },
  tableColumns: [
    {
      title: "标记",
      prop: "sign",
      sortable: false,
      slot: true
    },
    {
      title: "单位",
      prop: "orgname"
    },
    {
      title: "生产设备设施名称",
      prop: "name",
    },
    {
      title: "生产设备设施类型",
      prop: "sblx",
      slot: true
    },
    {
      title: "内部编号",
      prop: "nbbh"
    },
    {
      title: "所属场所部位",
      prop: "sitename",
      slot: true
    },
    {
      title: "具体位置",
      prop: "location"
    },
    {
      title: "品牌型号",
      prop: "brandModel"
    },
    {
      title: "投入使用日期",
      prop: "usertime"
    },
    {
      title: "接地情况",
      prop: "jdqk",
      slot: true
    },
    // {
    //   title: "安全装置数量",
    //   prop: "jdqk"
    // },
    {
      title: "责任部门",
      prop: "responsibilitydeptname"
    },
    {
      title: "责任人",
      prop: "responsibilitypersonname",
      slot: true
    },
    {
      title: "状态",
      prop: "state",
      slot: true
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],
  tableData: []
})
const fromObj = ref({ type: '1', ...pageData.listQuery })
// 重构后的变量 start
const getHeight = ref(null)
const totalHeight = ref(null)
const aqqcTotal = ref(null)
const keys = ref(0)
const isAuth = ref(false)
const sbsslist = ref([]);
const exportSheets = reactive(Produce)
const exportInfo = reactive({
  name: "生产设备设施",
  loading: false,
  disabled: false
})
const handleSelecTable = () => {

}
const searchArr = reactive([
  {
    showType: "input",
    prop: "keywords",
    width: '250px',
    placeholder: '请输入生产名称或内部编号',
  }, {
    showType: "zdlistTree",
    prop: "sblx",
    width: '250px',
    placeholder: '请选择设备设施类型',
    options: sbsslist,
  }, {
    showType: "input",
    prop: "siteName",
    width: '250px',
    placeholder: '请输入所属场所部位',
  },
]);
watch(() => props.isShowTotal, (val) => {
  nextTick(() => {
    if (val) {
      totalHeight.value = `calc(100vh - ${382 + getHeight.value.offsetHeight}px)`
      return
    }
    totalHeight.value = `calc(100vh - 382px)`
  })
}, {
  deep: true,
  immediate: true
})
function onSearch(obj) {
  pageData.listQuery.keywords = obj.keywords
  pageData.listQuery.sblx = obj.sblx
  pageData.listQuery.siteName = obj.siteName
  pageData.listQuery.pageCurrent = 1
  gettablist()
}
const getTreeItem = (treeData, id) => {
  for (let i in treeData) {
    if (treeData[i].dm === id) {
      return treeData[i]
    }
    if (treeData[i].itemList && treeData[i].itemList.length) {
      var res = getTreeItem(treeData[i].itemList, id)
      if (res) return res
    }
  }
}
// 导出
const getSheets = go => {
  pageData.listQuery.pageSize = 1e5 //取1W
  exportInfo.loading = true
  exportSheets.forEach(item => {
    if (!item.title.includes(store.state.user.currentDeptName)) item.title = store.state.user.currentDeptName + item.title
    item.data = []
  })
  postApi({ ...pageData.listQuery }, "/mosty-jcgl/sbglScsbss/exportTbSbglScsbss").then(res => {
    if (!res) {
      exportInfo.loading = false
      return
    }
    res.forEach(list => {
      if (list.floorname) {
        list.sitename = list.sitename + "-" + list.buildingname + "-" + list.floorname + "-" + list.partname
      } else {
        if (list.sitename && list.buildingname && list.partname) {
          list.sitename = list.sitename + "-" + list.buildingname + "-" + list.partname
        } else {
          list.sitename = ''
        }
      }
      if (getTreeItem(sbsslist.value, list.sblx)?.dm) {
        exportSheets.forEach(item => {
          if (item.code === getTreeItem(sbsslist.value, list.sblx)?.dm) item.data.push(list)
        })
      }
    })
    setTimeout(() => {
      exportInfo.loading = false
      go()
    }, 3e2)
  })
}

// 是否可以操作
const isAuthorize = async () => {
  isAuth.value = await getAuth()
}
//获取设备设施类型
const getsblb = () => {
  let diningHallArr = ['200404020000', '200404030000', '200404050000', '200404070000', '200404080000', '200404090000', '200404100000', '200404110000']
  getApi({ zdbh: 'D_TB_JCYWLX', dm: '2004', level: 5 }, '/mosty-base/sysDict/getJcyelxDictTree').then(res => {
    let arr = Array.isArray(res?.[0]?.itemList) ? res[0].itemList : []
    // 不包含食堂数据
    sbsslist.value = arr.map(item => {
      if (Array.isArray(item.itemList)) {
        item.itemList = item.itemList.filter(child => {
          return !diningHallArr.includes(child.dm)
        })
      }
      return item
    })
  })
}

onMounted(() => {
  isAuthorize()
  getsblb()
  nextTick(() => {
    totalHeight.value = `calc(100vh - ${382 + getHeight.value.offsetHeight}px)`
  })
  if (props.type == 'cs') {
    pageData.listQuery.siteid = props.obj.id
    fromObj.value.siteid = props.obj.id
    gettablist()
  } else if (props.type == 'jzw') {
    pageData.listQuery.buildingid = props.obj.id
    fromObj.value.buildingid = props.obj.id
    gettablist()
  } else if (props.type == 'lc') {
    pageData.listQuery.floorid = props.obj.id
    fromObj.value.floorid = props.obj.id
    gettablist()
  } else if (props.type == 'bw') {
    pageData.listQuery.partid = props.obj.id
    fromObj.value.partid = props.obj.id
    gettablist()
  } else if (props.type == 'scsbss') {
    pageData.listQuery.pageSize = 20
    watch(
      () => props.obj.orgid,
      (newValue) => {
        if (newValue) {
          pageData.listQuery.orgcode = newValue
          fromObj.value.orgcode = newValue
          fromObj.value.type = '0'
          pageData.listQuery.type = '0'
          gettablist()
        }

      },
      { deep: true, immediate: true }
    );
  } else if (props.type == 'stsbss') {
    showadd.value = props.obj.showadd
    pageData.listQuery.pageSize = 20
    watch(
      () => props.obj.orgid,
      (newValue) => {
        if (newValue) {
          pageData.listQuery.orgcode = newValue
          fromObj.value.orgcode = newValue
          pageData.listQuery.sblx = '200404000000'
          fromObj.value.type = '0'
          pageData.listQuery.type = '0'
          gettablist()
        }

      },
      { deep: true, immediate: true }
    );
  }


})
//生产设备设施分页查询
function gettablist() {
  tableloading.value = true
  exportInfo.disabled = false
  postApi({ ...pageData.listQuery }, "/mosty-jcgl/sbglScsbss/queryTbSbglScsbss").then(async (res) => {
    if (res) {
      let table_Data = []

      keys.value++
      tableloading.value = false
      for (let i = 0; i < res.records.length; i++) {
        /** @type {Aarray} 工业梯台 */
        const gytd = ["200401130000", "200402030000", "200403090000"]
        // 工业梯台
        if (gytd.includes(res.records[i].sblx)) {
          table_Data.push(await singleObjectCheck(res.records[i], industrialLadder))
        } else {
          table_Data.push(await singleObjectCheck(res.records[i], bladeBlowingEquipment))
        }
      }
      pageData.tableData = table_Data
      pageData.listQuery.total = res.total
      if (res.records.length === 0) exportInfo.disabled = true
    }
  })
}

//新增
function addUserHander() {
  formData.value.type = props.type
  formData.value = {}
  pageData.listQuery.sblx = null
  if (props.type == 'cs') {
    formData.value.title = '生产设备设施新增';
    formData.value.siteid = props.obj.id
    formData.value.sitename = props.obj.placename
  } else if (props.type == 'jzw') {
    if (props.obj.type == 'cq') {
      formData.value.publicarea = '1'
    }
    formData.value.title = '生产设备设施新增';
    formData.value.siteid = props.obj.siteid
    formData.value.sitename = props.obj.sitename
    formData.value.buildingid = props.obj.id
    formData.value.buildingname = props.obj.buildingname
    formData.value.publicarea = props.obj.publicarea
  } else if (props.type == 'lc') {
    formData.value.title = '生产设备设施新增';
    formData.value.siteid = props.obj.siteid
    formData.value.sitename = props.obj.sitename
    formData.value.buildingid = props.obj.buildingid
    formData.value.buildingname = props.obj.buildingname
    formData.value.floorid = props.obj.id
    formData.value.floorname = props.obj.floorname
  } else if (props.type == 'bw') {
    if (props.obj.type == 'cq') {
      formData.value.sfcq = '1'
      formData.value.publicarea = '1'
    } else {
      if (props.obj.sfcq && props.obj.sfcq == '1') {
        formData.value.sfcq = '1'
        formData.value.publicarea = '1'
      } else {
        formData.value.sfcq = '2'
        formData.value.publicarea = '2'
      }
    }
    formData.value.title = '生产设备设施新增';
    formData.value.siteid = props.obj.siteid
    formData.value.sitename = props.obj.sitename
    formData.value.buildingid = props.obj.buildingid
    formData.value.buildingname = props.obj.buildingname
    formData.value.floorid = props.obj.floorid
    formData.value.floorname = props.obj.floorname
    formData.value.partid = props.obj.id
    formData.value.partname = props.obj.partname
    formData.value.qtmc = props.obj.qtmc ? props.obj.qtmc : null
  } else if (props.type == 'scsbss') {
    formData.value.title = '生产设备设施新增';
  } else if (props.type == 'stsbss') {
    formData.value.title = '食堂设备设施新增';
  }

  formData.value.saveBtnShow = true;
  addtzsbShow.value = true
  tableloading.value = false
}
//复制
function handlcopy(row) {
  if (props.type == 'stsbss') {
    formData.value.title = '食堂设备设施复制';
  } else {
    formData.value.title = '生产设备设施复制';
  }
  formData.value.type = props.type
  formData.value.qtmc = props.obj.qtmc ? props.obj.qtmc : null
  formData.value.id = row.id
  formData.value.xgfMc = row.xgfMc
  formData.value.xgfId = row.xgfId
  formData.value.xgfRyMc = row.xgfRyMc
  formData.value.xgfRyId = row.xgfRyId
  formData.value.saveBtnShow = true;
  addtzsbShow.value = true
}
//修改
function handlexg(row) {
  if (props.type == 'stsbss') {
    formData.value.title = '食堂设备设施修改';
  } else {
    formData.value.title = '生产设备设施修改';
  }
  formData.value.type = props.type
  formData.value.qtmc = props.obj.qtmc ? props.obj.qtmc : null
  formData.value.id = row.id

  formData.value.xgfMc = row.xgfMc
  formData.value.xgfId = row.xgfId
  formData.value.xgfRyMc = row.xgfRyMc
  formData.value.xgfRyId = row.xgfRyId


  formData.value.saveBtnShow = true;
  addtzsbShow.value = true
}
//查看
function handleSee(row) {
  if (props.type == 'stsbss') {
    formData.value.title = '食堂设备设施详情';
  } else {
    formData.value.title = '生产设备设施详情';
  }
  formData.value.type = props.type
  formData.value.qtmc = props.obj.qtmc ? props.obj.qtmc : null
  formData.value.id = row.id
  formData.value.saveBtnShow = false;
  addtzsbShow.value = true
}
//注销
function handledelete(row) {
  getApi({ id: row.id }, `/mosty-jcgl/sbglScsbss/deleteTbSbglScsbssOne`).then(res => {
    ElMessage.success("删除成功");
    emits("searchChange", 'scsb');
    gettablist()
  })
}
//关闭
const changePage = (obj) => {
  // formData.value = {}
  addtzsbShow.value = false
  // pageData.listQuery.sblx = null
  emits("searchChange", 'scsb');
  gettablist()
}

const createPage = (obj) => {
  formData.value = {}
  addtzsbShow.value = false
  pageData.listQuery.sblx = null
  pageData.listQuery.keywords = null
  pageData.listQuery.siteName = null
  resetFormRef.value.reset_form()
  pageData.listQuery.pageCurrent = 1
  emits("searchChange", 'scsb');
  gettablist()
}

//页码发生变化
const handleCurrentChange = (val) => {
  pageData.listQuery.pageCurrent = val;
  gettablist()
};
//查询条数发生变化
const handleSizeChange = (val) => {
  pageData.listQuery.pageSize = val;
  gettablist()
};
//批量导出二维码
function handleewm() {
  let url = '/mosty-api/mosty-jcgl/sbglScsbss/exportQrcodeZip?orgcode=' + pageData.listQuery.orgcode +
    (pageData.listQuery.keywords ? '&keywords' + pageData.listQuery.keywords : '') +
    (pageData.listQuery.siteName ? '&siteName' + pageData.listQuery.siteName : '') +
    (pageData.listQuery.sblx ? '&sblx' + pageData.listQuery.sblx : '')
  if (props.type == 'stsbss') {
    downloadewm(url, '食堂设备设施二维码')
  } else {
    downloadewm(url, '生产设备设施二维码')
  }


}
</script>

<style lang="scss" scoped>
::v-deep .el-divider--horizontal {
  margin: 12px 0;
}

.query-flex {
  display: flex;
  justify-content: space-between;

  .query-section {
    width: 68%;
  }

  .query-btn {
    width: 240px;
    display: flex;
    justify-content: flex-end;

    .toggle {
      height: 32px;
      cursor: pointer;
      display: flex;
      align-items: center;
      color: #0f3916;

      .el-icon {
        transform: rotate(90deg);
        transition: all 0.25s ease;
      }

      &.active {
        .el-icon {
          transform: rotate(-90deg);
        }
      }
    }
  }
}

.button {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}
</style>
