<template>
  <div>
    <SearchBox ref="SearchBoxRef" formName="selectTop" :formData="query" @showPop="showPop" @reset="reset"></SearchBox>
    <ButtonBox @search="handleSearch" @add="insertDialog" @start="start('0')" @remove="shutdwon('1')"></ButtonBox>

    <!--    <TableBox ref="TableBoxRef" :tableData="tableData" @edit="handleEdit" @remove="handleRemove" :page="pageType"-->
    <!--              :url="url" :param="query" @handleSelectionChange="handleSelectionChange"></TableBox>-->
    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange"
                :height="height">
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column type="index" label="序号" align="center" width="60" fixed="left">
          <template #default="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column v-if="true" prop="itemNm" label="物料名称" width="150" header-align="center" fixed="left"
                         align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-button @click="handleInfo(scope.row)" type="primary" link>{{ scope.row.itemNm }}</el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="itemCd" label="物料编码" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="status" label="生效状态" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status == 0">{{ formatterStr("status", scope.row.status) }}</el-tag>
            <el-tag type="info" v-else-if="scope.row.status == 1">{{
                formatterStr("status", scope.row.status)
              }}
            </el-tag>
            <el-tag v-else>{{ formatterStr("status", scope.row.status) }}</el-tag>
            <!--            <Selector :value="scope.row.status" :optionList="dicList.START_STATUS">-->
            <!--            </Selector>-->
          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="description" label="物料说明" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="purchaseFlag" label="可采购" width="150" header-align="center"
                         :formatter="formatter"
                         align="center" show-overflow-tooltip>
          <!--          <template #default="scope">-->
          <!--            <Selector :value="scope.row.purchaseFlag" :optionList="dictList.PURCHASE_FLAG">-->
          <!--            </Selector>-->
          <!--          </template>-->
        </el-table-column>
        <el-table-column v-if="true" prop="salesFlag" label="可销售" width="150" header-align="center"
                         :formatter="formatter"
                         align="center" show-overflow-tooltip>
          <!--          <template #default="scope">-->
          <!--            <Selector :value="scope.row.salesFlag" :optionList="dictList.SALES_FLAG">-->
          <!--            </Selector>-->
          <!--          </template>-->
        </el-table-column>
        <el-table-column v-if="true" prop="itemType" label="类别" width="150" header-align="center"
                         :formatter="formatter"
                         align="center" show-overflow-tooltip>
          <!--          <template #default="scope">-->
          <!--            <Selector :value="scope.row.itemType" :optionList="dictList.item_sort3">-->
          <!--            </Selector>-->
          <!--          </template>-->
        </el-table-column>
        <el-table-column v-if="true" prop="unit" label="计量单位" width="150" header-align="center"
                         :formatter="formatter"
                         align="center" show-overflow-tooltip>
          <!--          <template #default="scope">-->
          <!--            <Selector :value="scope.row.unit" :optionList="dictList.MEASURING_UNIT">-->
          <!--            </Selector>-->
          <!--          </template>-->
        </el-table-column>
        <el-table-column v-if="true" prop="addName" label="添加人" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="addTime" label="添加时间" width="200" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="orgId" label="公司ID" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="orgName" label="公司" width="150" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="200px" fixed="right">
          <template #default="scope">
            <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button plain type="danger" @click="handleRemove(scope.row )">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
                     background="background" layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>

    <el-dialog class="diaClass" :close-on-click-modal="false" draggable title="新增" v-model="insertDialogShow"
               width="40%"
               top="5vh">
      <el-card>
        <el-form ref="formRef" :model="insertForm" :rules="rules" label-width="110" label-position="right"
                 :inline="true">
          <el-row>
            <el-col :span="12">
              <el-form-item label="物料名称" prop="itemNm">
                <el-input v-model="insertForm.itemNm">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物料编码" prop="itemCd">
                <el-input v-model="insertForm.itemCd" disabled></el-input>
              </el-form-item>
            </el-col>
            <!--          <el-col :span="12">-->
            <!--            <el-form-item label="公司ID">-->
            <!--              <el-input v-model="insertForm.orgId"></el-input>-->
            <!--            </el-form-item>-->
            <!--          </el-col>-->
            <!--          <el-col :span="12">-->
            <!--            <el-form-item label="公司" prop="orgName">-->
            <!--              <el-input v-model="insertForm.orgName">-->
            <!--              </el-input>-->
            <!--            </el-form-item>-->
            <!--          </el-col>-->

            <el-col :span="24">
              <el-form-item label="物料说明" prop="description">
                <el-input
                    v-model="insertForm.description"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea"
                    placeholder=""
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="可采购" prop="purchaseFlag">
                <el-radio-group v-model="insertForm.purchaseFlag">
                  <el-radio v-for="item in dictList.PURCHASE_FLAG" :label="item.dicCode">{{ item.dicName }}</el-radio>
                </el-radio-group>
                <!--              <SelectorComponent :optionList="dictList.PURCHASE_FLAG" :value="insertForm.purchaseFlag"-->
                <!--                                 @change="purchaseFlagDict"/>-->
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="可销售" prop="salesFlag">
                <el-radio-group v-model="insertForm.salesFlag">
                  <el-radio v-for="item in dictList.SALES_FLAG" :label="item.dicCode">{{ item.dicName }}</el-radio>
                </el-radio-group>
                <!--              <SelectorComponent :optionList="dictList.SALES_FLAG" :value="insertForm.salesFlag"-->
                <!--                                 @change="salesFlagDict"/>-->
              </el-form-item>
            </el-col>


            <el-col :span="12">
              <el-form-item label="类别" prop="itemType">
                <SelectorComponent :optionList="dictList.item_sort3" :value="insertForm.itemType"
                                   @change="itemTypeDict"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计量单位" prop="unit">
                <SelectorComponent :optionList="dictList.MEASURING_UNIT" :value="insertForm.unit"
                                   @change="unitDict"/>
              </el-form-item>
            </el-col>


          </el-row>
        </el-form>

      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" plain @click="insertDialogSave(formRef)">保存</el-button>
          <el-button type="danger" plain @click="insertDialogShow = false">取消</el-button>
        </div>
      </template>


    </el-dialog>
    <el-dialog class="diaClass" :close-on-click-modal="false" draggable title="查看" v-model="detailsDialogShow"
               width="40%"
               top="5vh">
      <el-card>
        <el-form ref="formRef" :model="insertForm" :rules="rules" label-width="110" label-position="right"
                 :inline="true">
          <el-row>
            <el-col :span="12">
              <el-form-item label="物料名称" prop="itemNm">
                <el-input v-model="insertForm.itemNm" readonly>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物料编码" prop="itemCd">
                <el-input v-model="insertForm.itemCd" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="物料说明" prop="description">
                <el-input readonly
                          v-model="insertForm.description"
                          :autosize="{ minRows: 2, maxRows: 4 }"
                          type="textarea"
                          placeholder=""
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="可采购" prop="purchaseFlag">
                <el-radio-group v-model="insertForm.purchaseFlag">
                  <el-radio v-for="item in dictList.PURCHASE_FLAG" :label="item.dicCode" disabled>{{ item.dicName }}
                  </el-radio>
                </el-radio-group>
                <!--              <SelectorComponent :optionList="dictList.PURCHASE_FLAG" :value="insertForm.purchaseFlag"-->
                <!--                                 @change="purchaseFlagDict"/>-->
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="可销售" prop="salesFlag">
                <el-radio-group v-model="insertForm.salesFlag">
                  <el-radio v-for="item in dictList.SALES_FLAG" :label="item.dicCode" disabled>{{ item.dicName }}
                  </el-radio>
                </el-radio-group>
                <!--              <SelectorComponent :optionList="dictList.SALES_FLAG" :value="insertForm.salesFlag"-->
                <!--                                 @change="salesFlagDict"/>-->
              </el-form-item>
            </el-col>


            <el-col :span="12">
              <el-form-item label="类别" prop="itemType">
                <SelectorComponent :optionList="dictList.item_sort3" :value="insertForm.itemType" :allow-select="true"
                                   @change="itemTypeDict"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计量单位" prop="unit">
                <SelectorComponent :optionList="dictList.MEASURING_UNIT" :value="insertForm.unit" :allow-select="true"
                                   @change="unitDict"/>
              </el-form-item>
            </el-col>


          </el-row>
        </el-form>

      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" plain @click="detailsDialogShow = false">取消</el-button>
        </div>
      </template>


    </el-dialog>


  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance
} from 'vue'
import {Search} from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const {
  proxy
} = getCurrentInstance()

import SelectorComponent from "@/views/sal/components/Selector_component.vue";
import style from '@/tools/style'

const cardBodyStyle = ref(style.card)

const tableStatus = reactive({
  tableRowEditIndex: undefined,
  tableColumnEditIndex: undefined,
})
import SearchBar from '@/components/SearchBar.vue';

const searchBarRef = ref(null)
const formItem = ref([
  {
    prop: 'birthDate',
    type: 'input',
    label: '订单号'
  },
  {
    prop: 'age',
    type: 'input',
    label: '客户名称',
    searchButton: true,
    searchCallback: 'showPop'
  }

])

const searchForm = (val) => {
  query.value = searchBarRef.value.form
  console.log(JSON.stringify(query.value))
}

/**
 *   查询
 */

const query = ref({
  itemCd: '',
  itemNm: '',
})
// 首 列表
const tableData = ref([])
// 物料 列表
const tableDataWl = ref([])
const tableDataTwo = ref([])
const tableDataMx = ref([])

const url = ref("bas/Item/query")
const pageType = ref(true)

const TableBoxRef = ref(null)
const handleSearch = (val) => {
  currentPage.value = 1
  getTableData()
  // TableBoxRef.value.search()
}
const getTableData = () => {
  var url = 'bas/Item/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    itemCd: query.value.itemCd,
    itemNm: query.value.itemNm,
    status: query.value.status,
    params: JSON.stringify(query.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
/**
 *   查询
 */
/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([ 10, 20, 30, 40])
const pageSize = ref(10)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}
/**
 * 分页
 */

import PopupMenuTree from '@/components/PopupMenuTree.vue'
import ButtonBar from "@/components/ButtonBar.vue";
import SearchBox from "@/components/SearchBox.vue";
import ButtonBox from "@/components/ButtonBox.vue";
import Selector from "@/views/sal/components/Selector_text.vue";

const PopupMenuTreeRef = ref(null)
const showPop = () => {
  console.log('showPop')
  PopupMenuTreeRef.value.show()
}
/**
 * 新增表单form
 */
const insertForm = ref({
  id: '',
  itemNm: '',
  itemCd: '',
  orgId: '',
  orgName: '',
  description: '',
  purchaseFlag: '',
  salesFlag: '',
  itemType: '',
  unit: ''
})


// 新增
const insertDialogShow = ref(false)
const detailsDialogShow = ref(false)
const insertDialog = () => {
  insertDialogShow.value = true
  insertForm.value = {}

}
const detailsDialog = () => {
  detailsDialogShow.value = true


}
const insertDialogSave = (formRef) => {
  if (!formRef) return
  formRef.validate((valid) => {
    if (valid) {
      console.log('submit!')
      var url = 'bas/Item/save'
      var param = {
        json: JSON.stringify(insertForm.value),

      }
      proxy.$axios.post(url, param, "application/x-www-form-urlencoded").then(response => {
        if (response.data.code == 0) {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          insertDialogShow.value = false
          handleSearch()
        } else {
          ElMessage({
            type: 'error',
            message: '操作失败' + response.data.msg
          })
        }
      });
    } else {
      console.log('error submit!')
      return false
    }
  })
  console.log("insertForm.value", insertForm.value)

}


const start = (param) => {
  if (checkRow.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要生效的数据!'
    })
    return
  }
  edit('生效', param)

}
const shutdwon = (param) => {
  if (checkRow.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要失效的数据!'
    })
    return
  }
  edit('失效', param)

}

const edit = (title, val) => {
  var ids = []
  for (var i = 0; i < checkRow.value.length; i++) {
    ids.push(checkRow.value[i].id)
  }

  var param = {
    ids: JSON.stringify(ids),
    status: val
  }
  var url = 'bas/Item/startAndShutDown'
  ElMessageBox.confirm(
      '此操作将' + title + '该数据, 是否继续?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        proxy.$axios.post(url, param).then(response => {
          if (response.data.code == '0') {

            ElMessage({
              type: 'success',
              message: title + '成功！',
            });
            getTableData()
            // TableBoxRef.value.search()
          } else {
            ElMessage.error('操作失败！' + response.data.msg)
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })


}


// 提交审批
const submit = () => {
  insertDialogShow.value = false
  ElMessage({
    message: '模拟提交审批成功！',
    type: 'success',
  })

}
// 校验
const rules = reactive({
  itemNm: [
    {required: true, message: '不允许为空', trigger: 'blur'},
  ],
  itemType: [
    {required: true, message: '不允许为空', trigger: 'change'},
  ],
  unit: [
    {required: true, message: '不允许为空', trigger: 'change'},
  ],

})

const otherQuery = () => {

}

// 首-列表 编辑
const handleEdit = (row) => {
  if (row.status == '0') {
    ElMessage({
      type: 'warning',
      message: '数据生效中，不允许操作！'
    })
    return
  }
  var url = 'bas/Item/queryByPK'
  var param = {
    id: row.id
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      // Object.assign(insertForm, {
      //   ...response.data.data,
      // });
      insertForm.value = response.data.data
      insertDialogShow.value = true
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
  insertDialogShow.value = true
}

// 首-列表 编辑
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
}

// 调价申请物料 -add row、
const onAddItemWl = () => {
  const now = new Date()
  now.setDate(now.getDate() + 1)
  tableDataWl.value.push({
    id: now.getTime(),
    isEdit: false,
    itemCd: "",
    itemNm: "",
    startDt: "",
    priceCash: "",
  })
}
const tableRowInputRef = ref(null)
const rowEdit = (scope) => {
  scope.isEdit = true
}
const rowEditSave = (scope) => {
  scope.isEdit = false
}

// 表格中input取消焦点,select变化
const onInputTableBlur = (scope) => {
  console.log('取消焦点', scope)
  tableStatus.tableRowEditIndex = undefined
  tableStatus.tableColumnEditIndex = undefined
  const id = scope.row.id
  const key = scope.column.property
  const value = scope.row[key]
  // 更新给后端的数据接口
  // 提交数据........
}
const dictList = ref({})
const dictData = () => {
  var url = 'framework/Common/querySelectorList'
  var param = {
    type: JSON.stringify(['PURCHASE_FLAG', 'SALES_FLAG', 'item_sort3', 'MEASURING_UNIT', 'START_STATUS'])
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      dictList.value = response.data.data
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

const handleRemove = (row) => {
  if (row.status == '0' || row.status == '1') {
    ElMessage({
      type: 'warning',
      message: '不允许操作！'
    })
    return
  }
  var url = 'bas/Item/remove'
  var param = {
    id: row.id
  }
  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        proxy.$axios.get(url, param).then(response => {
          if (response.data.code == '0') {
            console.log(response.data.data)
            ElMessage({
              type: 'success',
              message: '删除成功！',
            });
            getTableData()
            // TableBoxRef.value.search()
          } else {
            ElMessage.error('操作失败！' + response.data.msg)
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })


}


// 选中行
const checkRow = ref([])
const handleSelectionChange = (val) => {
  checkRow.value = val
}

const formRef = ref();

const purchaseFlagDict = (val) => {
  insertForm.value.purchaseFlag = val
}
const salesFlagDict = (val) => {
  insertForm.value.salesFlag = val
}
const itemTypeDict = (val) => {
  insertForm.value.itemType = val
}
const unitDict = (val) => {
  insertForm.value.unit = val
}
const height = ref(600)
const updateViewportHeight = () => {
  height.value = window.innerHeight * 0.65
  console.log(window.innerHeight);
};
const formatterStr = (col, value) => {
  if (!value || value == null || value == '') {
    return value
  }
  switch (col) {
    case 'status':
      value = dictList.value && Array.isArray(dictList.value.START_STATUS)
          ? dictList.value.START_STATUS.find(item => item.dicCode == value)?.dicName
          : undefined
      break
  }
  return value

}


const formatter = (row, column, cellValue, index) => {
  if (!cellValue || cellValue == null || cellValue == '') {
    return cellValue
  }
  switch (column.property) {
    case 'status':
      cellValue = dictList.value && Array.isArray(dictList.value.START_STATUS)
          ? dictList.value.START_STATUS.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break
    case 'purchaseFlag':
      cellValue = dictList.value && Array.isArray(dictList.value.PURCHASE_FLAG)
          ? dictList.value.PURCHASE_FLAG.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break
    case 'salesFlag':
      cellValue = dictList.value && Array.isArray(dictList.value.SALES_FLAG)
          ? dictList.value.SALES_FLAG.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break
    case 'itemType':
      cellValue = dictList.value && Array.isArray(dictList.value.item_sort3)
          ? dictList.value.item_sort3.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break
    case 'unit':
      cellValue = dictList.value && Array.isArray(dictList.value.MEASURING_UNIT)
          ? dictList.value.MEASURING_UNIT.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break
  }
  return cellValue

}

const handleInfo = (row) => {
  detailsDialogShow.value = true
  insertForm.value = row

}

onMounted(() => {
  dictData()
  updateViewportHeight()
  getTableData()
  console.log(`the component is now mounted.`)
})
</script>

<style scoped>
::v-deep .diaClass .el-form-item {
  width: 100%
}

::v-deep .diaClass70 .el-form-item {
  width: 90%
}


.el-date-editor--date {
  width: 100%;
}

::v-deep .el-dialog__body {
  background-color: #F2F6FC;
}
</style>
