<template>
  <div class="page-container column-container">
    <section class="list-part-container column-container" style="flex: 2">
      <!-- 搜索区 -->
      <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true" mar>
        <el-form-item class="section-title" label="工艺文件下发及时率" />
        <el-form-item label="当前年 ">
          <el-date-picker v-model="queryParams.year" type="year" value-format="YYYY" placeholder="请选择年"
            :clearable="false" style="width: 140px; margin-left: 10px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="info" icon="Search" @click="handleQuery">
            搜索
          </el-button>
        </el-form-item>
      </el-form>
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table ref="statisticsTable" :data="statisticsList" v-loading="detailLoading" highlight-current-row
            height="100%" @current-change="handleStatisticsCurrentChange">
            <el-table-column label="年" prop="year" width="80" align="center" />
            <el-table-column label="月" prop="month" width="80" align="center" />
            <el-table-column label="实际完成个数" width="140" prop="finishedNum" align="center" />
            <el-table-column label="经营部下发规定时间完成次数" width="200" prop="finishedInTimeNum" align="center" />
            <el-table-column label="工艺文件下发及时率" width="160" prop="ratio" align="center">
              <template #default="scope">
                <div v-if="scope.row.ratio">{{ scope.row.ratio }}%</div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column></el-table-column>
          </el-table>
        </div>
      </div>
    </section>
    <!-- 分页 -->
    <section class="list-part-container row-container" style="flex: 3">
      <section class="list-part-container" style="flex: 4">
        <!-- 下边页面开始 -->
        <!-- 搜索区 -->
        <el-form class="list-search-container" :inline="true">
          <el-form-item class="section-title" :label="showType" />
          <el-form-item>
            <el-radio-group v-model="showType">
              <el-radio-button value="图表" label="图表">
              </el-radio-button>
              <el-radio-button value="详情" label="详情">
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button
              v-if="showType === '详情' && (checkPermi('business:processComplete:edit') || checkRole('business'))"
              @click="handleAdd" type="primary">新增</el-button>
          </el-form-item>
        </el-form>
        <div v-if="showType === '详情'" class="el-table-container">
          <div class="el-table-inner-container">
            <el-table ref="subDetailsTable" v-loading="subDetailsLoading" :data="detailList" highlight-current-row
              height="100%">
              <el-table-column type="index" label="行号" width="50" align="center" />
              <el-table-column label="经营下达日期" align="center">
                <template #default="scope">
                  <el-date-picker
                    v-if="scope.row.editStatus && (checkPermi('business:processComplete:edit') || checkRole('business'))"
                    v-model="scope.row.releaseDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期"
                    :clearable="false" style="width: 100%;" />
                  <div v-else>{{ scope.row.releaseDate }}</div>
                </template>
              </el-table-column>
              <el-table-column label="经营要求完成日期" align="center">
                <template #default="scope">
                  <el-date-picker
                    v-if="scope.row.editStatus && (checkPermi('business:processComplete:edit') || checkRole('business'))"
                    v-model="scope.row.planDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期"
                    :clearable="false" style="width: 100%;" @change="(arg) => handlePlanDateChange(arg, scope.row)" />
                  <div v-else>{{ scope.row.planDate }}</div>
                </template>
              </el-table-column>
              <el-table-column label="产品编码" align="center">
                <template #default="scope">
                  <el-input
                    v-if="scope.row.editStatus && (checkPermi('business:processComplete:edit') || checkRole('business'))"
                    v-model="scope.row.productCode" placeholder="请输入产品编码" style="width: 100%;" readonly>

                    <template #append>
                      <el-button icon="Search" @click="handleShowDialogProduct(scope.row)" />
                    </template>
                  </el-input>
                  <div v-else>{{ scope.row.productCode }}</div>
                </template>
              </el-table-column>
              <el-table-column label="产品描述" align="center">
                <template #default="scope">
                  <el-input
                    v-if="scope.row.editStatus && (checkPermi('business:processComplete:edit') || checkRole('business'))"
                    v-model="scope.row.productDescription" placeholder="请输入产品描述" style="width: 100%;" readonly />
                  <div v-else>{{ scope.row.productDescription }}</div>
                </template></el-table-column>
              <el-table-column label="技术实际完成日期" align="center">
                <template #default="scope">
                  <el-date-picker
                    v-if="scope.row.editStatus && (checkPermi('business:processComplete:edit') || checkRole('technician'))"
                    v-model="scope.row.actualDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期"
                    :clearable="false" style="width: 100%;" @change="handleActualChange(scope.row)" />
                  <div v-else>{{ scope.row.actualDate }}</div>
                </template>
              </el-table-column>
              <el-table-column label="是否超期" align="center">
                <template #default="scope">
                  {{ scope.row.isOverdue == 0 ? '未完成' : scope.row.isOverdue == 1 ? '否' : '是' }}
                </template>
              </el-table-column>
              <el-table-column label="未完成原因" align="center">
                <template #default="scope">
                  <el-input
                    v-if="scope.row.editStatus && (checkPermi('business:processComplete:edit') || checkRole('technician'))"
                    v-model="scope.row.reason" placeholder="请输入未完成原因" style="width: 100%;" />
                  <div v-else>{{ scope.row.reason }}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160" align="center">
                <template #default="scope">
                  <el-button v-if="scope.row.editStatus" type="success" @click="handleSave(scope.row)">保存</el-button>
                  <el-button
                    v-else-if="(checkPermi('business:processComplete:edit') || checkRole('business') || checkRole('technician'))"
                    type="primary" @click="() => scope.row.editStatus = true">编辑</el-button>
                  <el-button v-if="scope.row.editStatus" type="danger"
                    @click="() => scope.row.editStatus = false">取消</el-button>
                  <el-button v-else-if="(checkPermi('business:processComplete:edit') || checkRole('business'))"
                    type="danger" @click="handleDel(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div v-show="showType === '图表'" class="el-table-container">
          <div class="el-table-inner-container">
            <div ref="echartDom" id="echartDom" :style="{ height: '100%', width: '100%' }" />
          </div>
        </div>
        <pagination v-if="showType === '详情'" v-show="detailTotal > 0" :total="detailTotal"
          v-model:page="rowQuery.pageNum" v-model:limit="rowQuery.pageSize" @pagination="getDetailList" />
      </section>

    </section>
    <dialog-products ref="dialogProductsRef" :singleSelected="handlProductChocie" />
    <dialog-detail ref="dialogDetailRef" />
  </div>
</template>
<script setup name="ProcessComplete">
import { ref } from "vue";
import DialogProducts from "./DialogProducts.vue";
import DialogDetail from "./DialogDetail.vue";
import useUserStore from '@/store/modules/user'
// import productionDialog from "./DialogProduction";
import { listCompletion, listStatistics, getCompletion, addCompletion, updateCompletion, delCompletion } from '@/api/business/processCompletion'
const { proxy } = getCurrentInstance();
/** 字典数组区 */
const { lot_code_status_code } = proxy.useDict("lot_code_status_code");
/** 生产计划 */
const currentPlanDetail = ref({});
const statisticsList = ref([]);
const detailLoading = ref(false);
const total = ref(0);
const detailTotal = ref(0)
/** 工段 */
const loading = ref(false);
const deptList = ref([]);
/** 生产子计划 */
const detailList = ref([]);
const flag = ref(false);
const subDetailsLoading = ref(false);
const showType = ref('图表')
const currentRow = ref(null)
const statisticsTable = ref(null)
const choiceRow = ref(null)
const refreshedRow = ref(null)
let mychart = null
const dialogDetailRef = ref(null)
/** 查询对象 */
const queryParams = ref({
  year: proxy.moment().format('YYYY'),
  pageNum: 1,
  pageSize: 20,
});

const rowQuery = ref({
  pageNum: 1,
  pageSize: 10,
})
const months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']

const data = reactive({
  options: {
    title: { text: '工艺文件下发及时率', subtext: `${queryParams.value.year}年`, po: 'center' },

    grid: [{
      top: 80,
      right: 30,
      left: 30,
      bottom: 30
    }],
    xAxis: {
      type: 'category',
      data: months,
      // axisLabel: {
      //   interval: 0,
      //   rotate: 30
      // }
    },
    yAxis: {
      type: 'value',
      gridIndex: 0
    },
    series: []
  }
})
const { options } = toRefs(data)
function getList() {
  listStatistics(queryParams.value).then(res => {
    if (res.code === 200) {
      statisticsList.value = res.rows
      nextTick(() => {
        // console.log(refreshedRow.value)
        if (refreshedRow.value != null) {
          let index = statisticsList.value.findIndex(item => item.year == refreshedRow.value.year && item.month == refreshedRow.value.month)
          statisticsTable.value.setCurrentRow(statisticsList.value[index < 0 ? 0 : index])
          refreshedRow.value = null
        } else {
          statisticsTable.value.setCurrentRow(statisticsList.value[0])
        }
      })
      initData()
    }
  })
}

function showTooltipFormatter(params) {
  const month = String(months.findIndex(e => e === params[0].axisValue) + 1).padStart(2, '0')
  const data = statisticsList.value.find(e => e.month == month)
  // const data = monthlyData.find(e => e.month == params[0].axisValue)
  return `${params[0].axisValue}:<br/>
                本月实际完成数量${data.finishNum}，<br/>
                本月及时完成数量${data.finishedInTimeNum}，<br/>
                工艺完成率：${data.ratio}%`
  // return '测试'
}

function getDetailList() {
  if (currentRow.value != null) {
    rowQuery.value.year = currentRow.value.year
    rowQuery.value.month = currentRow.value.month
    listCompletion(rowQuery.value).then(res => {
      detailList.value = res.rows
      detailTotal.value = res.total
    })
  } else {
    detailList.value = []
  }
}

function handleStatisticsCurrentChange(row) {
  // console.log(row)
  currentRow.value = row
  getDetailList()
}

function handleAdd() {
  detailList.value.push({
    editStatus: true
  })
}

function handlePlanDateChange(arg, row) {
  row.year = proxy.moment(arg).format('YYYY')
  row.month = proxy.moment(arg).format('MM')
  handleActualChange(row)
}

function handleActualChange(row) {
  // 判断当完成日期大于计划日期时显示超期
  if (row.planDate != null && row.planDate != '' && row.actualDate != null && row.actualDate != '' && proxy.moment(row.planDate).isBefore(proxy.moment(row.actualDate))) {
    row.isOverdue = 2
  } else if (row.planDate != null && row.planDate != '' && row.actualDate != null && row.actualDate != '' && proxy.moment(row.planDate).isSameOrAfter(proxy.moment(row.actualDate))) {
    row.isOverdue = 1
  } else {
    row.isOverdue = 0
  }
}

function handlProductChocie(info) {
  choiceRow.value.productId = info.id
  choiceRow.value.productCode = info.productCode
  choiceRow.value.productDescription = info.description
  choiceRow.value.companyId = info.companyId
  choiceRow.value.companyCode = info.companyCode
  choiceRow.value.companyAlias = info.companyAlias
  choiceRow.value.specification = info.specification
  choiceRow.value.drawingNumber = info.drawingNumber
}

function handleShowDialogProduct(row) {
  choiceRow.value = row
  proxy.$refs.dialogProductsRef.open(row)
}

function handleSave(row) {
  // console.log(number.value);
  if (row.productId == null) {
    proxy.$modal.msgError('请选择产品')
    return
  }
  if (row.planDate == null || row.planDate == '') {
    proxy.$modal.msgError('请选择经营要求完成日期')
    return
  }
  if (row.releaseDate == null || row.releaseDate == '') {
    proxy.$modal.msgError('请选择经营下达日期')
    return
  }
  if (row.isOverdue == 2 && (row.reason == null || row.reason == '')) {
    proxy.$modal.msgError('请填写超期原因')
    return
  }
  if (row.id != null) {
    updateCompletion(row).then(res => {
      if (res.code === 200) {
        refreshedRow.value = currentRow.value
        getList()
      }
    })
  } else {
    addCompletion(row).then(res => {
      if (res.code === 200) {
        refreshedRow.value = currentRow.value
        getList()
      }
    })
  }
}

function handleDel(row) {
  proxy.$modal
    .confirm("确认删除吗？")
    .then(function () {
      delCompletion(row.id).then(res => {
        if (res.code === 200) {
          refreshedRow.value = currentRow.value
          getList()
        }
      })
    })
}

function handleQuery() {
  getList()
}

function initChart() {
  nextTick(_ => {
    if (mychart == null) {
      mychart = proxy.echarts.init(document.getElementById('echartDom'))
      // console.log(mychart.value)
    }
    mychart.setOption(options.value)
    mychart.on('click', e => {
      console.log(e)
      dialogDetailRef.value.open({ year: queryParams.value.year, month: String(months.findIndex(t => t === e.name) + 1).padStart(2, '0') })
    })
  })
}

function initData() {
  let values = []
  months.forEach((item, index) => {
    const i = statisticsList.value.find(e => (Number(e.month) - 1) === index)
    values.push(i == null ? 0 : i.ratio)
  })
  options.value.title.subtext = `${queryParams.value.year}年`
  // options.value.yAxis.data = values
  options.value.series = [{
    type: 'line',
    name: '工艺文件下发及时率',
    data: values
  }]
  // options.value.tooltip.formatter = '测试'
  options.value.tooltip = {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    show: true,
    formatter: function (params) {
      // console.log(params)
      const month = String(months.findIndex(e => e === params[0].axisValue) + 1).padStart(2, '0')
      const data = statisticsList.value.find(e => e.month == month)
      // const data = monthlyData.find(e => e.month == params[0].axisValue)
      return `${params[0].axisValue}:<br/>
                本月实际完成数量${data != null ? data.finishedNum : 0}，<br/>
                本月及时完成数量${data != null ? data.finishedInTimeNum : 0}，<br/>
                工艺完成率：${data != null ? data.ratio : 0}%`
    }
  }
  // console.log(options.value)
  initChart()
}

function checkPermi(arg) {
  const permissions = useUserStore().permissions
  const all_permission = "*:*:*";
  const hasPermission = permissions.some(permission => {
    return all_permission === permission || permission === arg
  })
  return hasPermission;
}

function checkRole(arg) {
  const roles = useUserStore().roles
  const hasRole = roles.some(role => {
    return role === arg
  })
  return hasRole;
}

initChart()
getList()
</script>
<style scoped>
.list-search-container-child .el-form-item {
  /* 修改样式 */
  margin-right: 10px;
}
</style>
