<template>
  <div>
    <div class="position">
      <BreadCrumb :crumbs="crumbs"></BreadCrumb>
    </div>
    <div class="app-container">
      <div style="display: flex;justify-content: space-between;margin-bottom:10px;">
        <div class="cell clearfix">
          <span>入库时间:</span>
          <el-date-picker
            size="small"
            v-model="start_time"
            prefix-icon="el-icon-date"
            :editable="false"
            style="width: 196px;"
            type="date"
            placeholder="选择日期时间"
            align="right"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>-
          <el-date-picker
            size="small"
            v-model="end_time"
            prefix-icon="el-icon-date"
            :editable="false"
            style="width: 196px;margin-right:10px;"
            type="date"
            placeholder="选择日期时间"
            align="right"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </div>
        <div>
          <span>销售状态:</span>
          <el-select size="small" v-model="is_sale" placeholder="请选择"
                    style="width:100px;" @change="changeStock">
            <el-option
              label="不限"
              value="3">
            </el-option>
            <el-option
              v-for="item,index in items"
              :key="index"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>

        <div>
          <el-button type="primary" @click="query()">查询</el-button>
          <el-button type="primary" @click="change_stock()">批量销售上传</el-button>
          <el-button type="primary" @click="exportdata()">导出</el-button>

          <!--        <el-button type="primary" @click="change()">变更</el-button>-->
        </div>
      </div>
      <el-table :data="tableData" border :row-style="{ color: '#303133' }" ref="table2"
              :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}"
              max-height="600"
              @select="selectCostInfo"
              @selection-change="changeCostInfoTableData"
              @select-all="changeAllCostInfoTableData"
              highlight-current-row>
        <el-table-column
          align="center"
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column align="center" prop="name" label="药品名称">
          <template slot-scope="scope">{{scope.row.drug_name}}</template>
        </el-table-column>

        <el-table-column align="center" prop="name" label="规格单位">
          <template slot-scope="scope">{{scope.row.spec}}</template>
        </el-table-column>

        <el-table-column  align="center" prop="name" label="追溯码">
          <template slot-scope="scope">
              <div @click="getDrugCode(scope.row.advice_id,scope.row.drug_code,scope.$index)"><el-input style="width: 100;" v-model="scope.row.drug_code"></el-input></div>
            </template>
          <!-- <template slot-scope="scope">{{scope.row.drug_code}}</template> -->
        </el-table-column>

        <el-table-column align="center" prop="name" label="患者姓名">
          <template slot-scope="scope">
            <!-- {{scope.row.p.name}} -->
            {{ getPatientName(scope.row.patient_id) }}
          </template>
        </el-table-column>

        <el-table-column align="center" prop="name" label="批号">
          <template slot-scope="scope">{{scope.row.batch_number}}</template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="数量">
          <template slot-scope="scope">
            <div>{{scope.row.count}}{{scope.row.unit}}</div>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="total" label="开方日期">
          <template slot-scope="scope">
            <div>{{scope.row.p_date}}</div>
          </template>
        </el-table-column>


        <el-table-column align="center" prop="total" label="销售状态">
          <template slot-scope="scope">
            <div>{{scope.row.is_sale?'已销售':'未销售'}}</div>
          </template>
        </el-table-column>



        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.is_sale || scope.row.is_sale == 0" type="primary" @click="sigle_stock(scope.row)">销售上传</el-button>
            <el-button v-if="scope.row.is_sale == 1" type="warning" @click="deleteStock(scope.row)">撤销</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-size="5"
        :page-sizes="[10, 20, 50, 100,500,1000,2000]"
        background
        style="margin-top:20px;float: right"
        :total="value"
      ></el-pagination>

      <el-table v-show="false" :data="tableData" border :row-style="{ color: '#303133' }" ref="table"
                :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}"
                max-height="600"
                @select="selectCostInfo"
                @selection-change="changeCostInfoTableData"
                @select-all="changeAllCostInfoTableData"
                highlight-current-row>
        <el-table-column
          align="center"
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column align="center" prop="name" label="药品名称">
          <template slot-scope="scope">{{scope.row.drug_name}}</template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="药品类型">
          <template slot-scope="scope">{{scope.row.drug_type}}</template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="规格单位">
          <template slot-scope="scope">{{scope.row.spec}}</template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="国家编码">
          <template slot-scope="scope">{{scope.row.code}}</template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="批号">
          <template slot-scope="scope">{{scope.row.batch_number}}</template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="数量">
          <template slot-scope="scope">
            <div>{{scope.row.count}}{{scope.row.unit}}</div>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="total" label="开方日期">
          <template slot-scope="scope">
            <div>{{scope.row.p_date}}</div>
          </template>
        </el-table-column>


        <el-table-column align="center" prop="total" label="结算日期">
          <template slot-scope="scope">
            <div>{{scope.row.e_date}}</div>
          </template>
        </el-table-column>




      </el-table>
    </div>
    <el-dialog
        title="药品追溯码"
        :visible.sync="dialogVisibleOne"
         width="40%">
       <span>
        <el-input
          @keyup.native="changeText"
          type="textarea"
          placeholder="请输入内容"
          v-model="textarea"
          :rows="10"
        >
        </el-input>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleOne = false">取 消</el-button>
        <el-button type="primary" @click="saveTextArea()">确 定</el-button>
      </span>
    </el-dialog>

  </div>

  <!-- </div> -->
</template>


<script>
import BreadCrumb from '@/xt_pages/components/bread-crumb'
import { GetDrugChangeStock } from '../../api/new_stock/stock'
import { getDictionaryDataConfig } from "@/utils/data";
import { uParseTime } from '@/utils/tools'
import { changeDrugCode } from "@/api/pharmacy";
import axios from 'axios'
const moment = require('moment')
export default {
  components: {
    BreadCrumb
  },
  data() {
    return {
      drugTypeList: [{ id: 0, name: "全部" }],
      start_time: new Date(new Date().getFullYear(), new Date().getMonth(), 1).toLocaleDateString('en-CA'),
      end_time: new Date(new Date().getFullYear(), new Date().getMonth() + 3, 0).toLocaleDateString('en-CA'),

      tableData: [],
      change_type:"3",
      selection:[],
      page:1,
      limit:10,
      value:0,
      is_sale:"3",
      items: [
        { id: 1, name: '已销售' },
        { id: 2, name: '已销售退货' },

      ],
      changes: [
        { id: 1, name: '已变更' },
        { id: 2, name: '未变更' },
      ],
      textarea:'',
      dialogVisibleOne:false,
      currentRow:{},
      currentIndex:0,
      patientList:[],
      crumbs: [
        { path: false, name: '药品追溯' },
        { path: false, name: '药品销售' }
      ],
    }
  },
  methods: {
     changeText(event){
        // 检查是否为特定的按键，例如回车键，来确认扫码枪输入完成
        if (event.key === 'Enter') {
            var textarea = ""
            textarea += this.textarea + ","
            this.textarea = textarea
        }
       },
       getDrugCode(id,DrugCode,index){
            this.id = id
            this.textarea = DrugCode
            this.currentIndex = index
            this.dialogVisibleOne = true
      },
      saveTextArea(){
        var str = this.textarea.replace(/\s+/g, '')
       console.log("str000000000000000",str)

       // 1. 分割字符串并过滤空值
      const numbers = str.split(',').filter(item => item.trim() !== '');

      // 2. 统计每个数字出现的次数
      const countMap = numbers.reduce((acc, num) => {
        // 由于数字很大，用字符串作为键
        const key = num.trim();
        acc[key] = (acc[key] || 0) + 1;
        return acc;
      }, {});

      // 3. 转换为要求的格式数组
      const result = Object.entries(countMap).map(([name, count]) => ({
        name,  // 保持字符串形式，因为数字太大可能丢失精度
        count
      }));

      console.log("result-----",result);
       var params = {
        id:this.id,
        data_source:1,
        drug_code:this.textarea,
        codeinfo:result
       }
       console.log("paramss",params)
      changeDrugCode(params).then(response=>{
         if(response.data.state == 1){
            this.$message.success("保存成功!")
            for(let i=0;i<this.tableData.length;i++){
             if(this.currentIndex == i){
                this.tableData[i].drug_code = this.textarea
             }
            }
            this.dialogVisibleOne = false
         }
      })
    },
    deleteStock(row){
      let ids  = row.id
      var that = this;
      let params = {
        ids:ids,
        admin_user_id:this.$store.getters.xt_user.user.id
      };
      axios.get('http://127.0.0.1:9532/test/net',{}).then(function(response) {
        if (response.data.state == 0) {
          // that.$message.error(response.data.data.msg);
          that.$confirm("请检查医保程序是否有打开", "提示", {
            confirmButtonText: "确 定",
            cancelButtonText: "取 消",
            type: "warning",
          }).then(() => {
            axios.get('http://127.0.0.1:9532/api/delete_xs_bg',{params:params}).then(function(response) {
              if (response.data.state == 0) {
                that.$message.error(response.data.data.msg);
                return false
              } else {
                if(response.data.data.failed_code == -10){
                  that.$confirm(response.data.data.msg, '医保错误信息', {
                    confirmButtonText: '确 定',
                    type: 'warning'
                  }).then(() => {

                  }).catch(() => {
                  })
                }else{
                  that.GetDrugStock()

                }
              }
            }).catch(function(error) {
            })

          })
            .catch(() => {});
          return false
        } else {

        }
      }).catch(function(error) {
        that.$confirm("请检查医保程序是否有打开", "提示", {
          confirmButtonText: "确 定",
          cancelButtonText: "取 消",
          type: "warning",
        }).then(() => {
        })
          .catch(() => {});
      })

    },
    sigle_stock(row){
       if(row.drug_code.length == 0){
         this.$message.error("追溯码不能为空");
         return
       }
      var that = this;
      let params = {
        ids:row.id,
        admin_user_id:this.$store.getters.xt_user.user.id
      };

      axios.get('http://127.0.0.1:9532/test/net',{}).then(function(response) {
        if (response.data.state == 0) {
          // that.$message.error(response.data.data.msg);
          that.$confirm("请检查医保程序是否有打开", "提示", {
            confirmButtonText: "确 定",
            cancelButtonText: "取 消",
            type: "warning",
          }).then(() => {


          })
            .catch(() => {});
          return false
        } else {

          axios.get('http://127.0.0.1:9532/api/changedrug',{params:params}).then(function(response) {
            if (response.data.state == 0) {
              that.$message.error(response.data.data.msg);
              return false
            } else {
              if(response.data.data.failed_code == -10){
                that.$confirm(response.data.data.msg, '医保错误信息', {
                  confirmButtonText: '确 定',
                  type: 'warning'
                }).then(() => {
                }).catch(() => {
                })
              }else{


              }
            }
          }).catch(function(error) {
          })
        }
      }).catch(function(error) {
        that.$confirm("请检查医保程序是否有打开", "提示", {
          confirmButtonText: "确 定",
          cancelButtonText: "取 消",
          type: "warning",
        }).then(() => {
        })
          .catch(() => {});
      })

    },
    handleSizeChange(val) {
      this.limit = val
      this.GetDrugStock()
    },
    handleCurrentChange(val) {
      this.page = val
      this.GetDrugStock()
    },
    selectCostInfo(selection, row) {
      this.selection = selection
    }, changeCostInfoTableData(val) {
      this.selection = val
    }, changeAllCostInfoTableData(selection) {
      this.selection = selection
    },
    delete(){


    },
    exportdata(){
      let list = []
      // for (let i = 0; i < this.tableData.length; i++) {
      //   let order = this.tableData[i]
      //   let name = order.name
      //   let item_name = order.item_name
      //   let count = order.count
      //   let price = order.price.toFixed(2)
      //   let pay_sumamt = (order.price.toFixed(2) * order.count).toFixed(2)
      //   let total = order.total.toFixed(2)
      //
      //   let obj = {
      //     '患者姓名': name,
      //     '项目名称': item_name,
      //     '数量': count,
      //     '单价': price,
      //     '费用': pay_sumamt,
      //     '费用总额': total
      //   }
      //   list.push(obj)
      // }
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['患者姓名', '项目名称', '数量', '单价', '费用', '费用总额']
        const filterVal = ['患者姓名', '项目名称', '数量', '单价', '费用', '费用总额']
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel1({
          header: tHeader,
          data,
          filename: '明细',
          ref: this.$refs['table'].$el
        })
      })

    },formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    change_stock(){
      let ids  = ""
      for (var i = 0; i < this.selection.length; i++){
        if (ids.length == 0){
          ids = this.selection[i].id
        }else{
          ids = ids + "," + this.selection[i].id
        }
      }
      if(ids.length == 0 ){
        this.$message.error("请勾选需要上传的数据");
        return
      }

      var that = this;
      let params = {
        ids:ids,
        admin_user_id:this.$store.getters.xt_user.user.id
      };

      axios.get('http://127.0.0.1:9532/test/net',{}).then(function(response) {
        if (response.data.state == 0) {
          // that.$message.error(response.data.data.msg);
          that.$confirm("请检查医保程序是否有打开", "提示", {
            confirmButtonText: "确 定",
            cancelButtonText: "取 消",
            type: "warning",
          }).then(() => {
          })
            .catch(() => {});
          return false
        } else {
          axios.get('http://127.0.0.1:9532/api/changedrug',{params:params}).then(function(response) {
            if (response.data.state == 0) {
              that.$message.error(response.data.data.msg);
              return false
            } else {
              if(response.data.data.failed_code == -10){
                that.$confirm(response.data.data.msg, '医保错误信息', {
                  confirmButtonText: '确 定',
                  type: 'warning'
                }).then(() => {
                }).catch(() => {
                })
              }else{

              }
            }
          }).catch(function(error) {
          })
        }
      }).catch(function(error) {
        that.$confirm("请检查医保程序是否有打开", "提示", {
          confirmButtonText: "确 定",
          cancelButtonText: "取 消",
          type: "warning",
        }).then(() => {
        })
          .catch(() => {});
      })







    },
    query(){
      this.GetDrugStock()

    },
    change(){


    },getDrugType(id) {
      var name = "";
      for (let i = 0; i < this.drugTypeList.length; i++) {
        if (this.drugTypeList[i].id == id) {
          name = this.drugTypeList[i].name;
        }
      }

      return name;
    },  getTime(val) {
      if(val == "" || val == undefined){
        return ""
      }else {
        return uParseTime(val, '{y}-{m}-{d}')
      }
    },GetDrugStock(){
      this.tableData = []
      let params = {
        start_time: this.start_time,
        end_time: this.end_time,
        page:this.page,
        limit:this.limit,
        is_sale:this.is_sale,
        is_bg:this.change_type
      }
      GetDrugChangeStock(params).then(response => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg)
          return false
        } else {
          this.value = response.data.data.total
          this.patientList =  response.data.data.patientList
          for(let i =0; i < response.data.data.info.length; i++){
            let obj = {
              id:response.data.data.info[i].id,
              drug_name:response.data.data.info[i].BaseDrugLib.drug_name,
              drug_type:this.getDrugType(response.data.data.info[i].BaseDrugLib.drug_type),
              spec: response.data.data.info[i].BaseDrugLib.dose + response.data.data.info[i].BaseDrugLib.dose_unit + "*" + response.data.data.info[i].BaseDrugLib.min_number + response.data.data.info[i].BaseDrugLib.min_unit+"/" +response.data.data.info[i].BaseDrugLib.max_unit,
              code:response.data.data.info[i].BaseDrugLib.medical_insurance_number,
              batch_number:response.data.data.info[i].batch_number,
              count: response.data.data.info[i].PCount,
              p_date:this.getTime(response.data.data.info[i].PDate),
              e_date:(response.data.data.info[i].SDate),
              is_sale:response.data.data.info[i].is_sale,
              pc_date:response.data.data.info[i].pc_date,
              is_bg:response.data.data.info[i].is_change,
              unit:response.data.data.info[i].Unit,
              patient_id:response.data.data.info[i].patient_id,
              drug_code:response.data.data.info[i].his_advice_info.drug_code,
              advice_id:response.data.data.info[i].his_advice_info.id
            }
            this.tableData.push(obj)
          }
        }
      })
    },
    changeStock(){


    },
    getPatientName(id){
      console.log("id=-=--------------",id)
      console.log("patinetlist===========",this.patientList)
      var name = ""
      for(let i=0;i<this.patientList.length;i++){
        if(id == this.patientList[i].id){
          name = this.patientList[i].name
        }
      }
      return name
    }
  },
  created() {
    var drugTypeList = getDictionaryDataConfig("system", "drug_type");
    this.drugTypeList.push(...drugTypeList);
  this.GetDrugStock()
  }
}
</script>

