<template>
  <div>
    <el-dialog top="5vh" :title="staffTitle" :visible.sync="staffDialogVisible" width="900px"
      :close-on-click-modal="false" @close="closePopup">
      <div class="waybill_item">
        <waybillForm ref="recipients" title="患者信息" :conserveFlag="conserveFlag" thinTitle="患者簿"
          :ruleForm="recipientsForm" @addressBook="getAddressBook('recipients')" @conserveSelect="conserveSelectil">
        </waybillForm>
      </div>
      <forms ref="childRules" :formNewList="formRuleList" :ruleForm="ruleForm" :delDrug="true" labelWidth="80px">
      </forms>
      <el-dialog width="60%" title="地址簿" :visible.sync="innerVisible" append-to-body>
        <div class="space_between_in" style="margin-bottom: 15px;">
          <div style="display: flex;align-items: center;width: 100%;">
            <h3 style="margin-left: 10px;flex: none;">搜索：</h3>
            <el-input v-model="bookInput" style="width: 100%;" placeholder="请输入姓名、电话、地址快速查找"
              @input="fastSearch()"></el-input>
          </div>
        </div>
        <div class="card_book_list">
          <!-- 表单 -->
          <tables :suspension="true" :tableList="bookTableList" :tableData="bookTableData" @cellClick="cellClick">
          </tables>
          <!-- 分页 -->
          <div v-if="bookTotal">
            <pagination :total="bookTotal" :currentPage="bookPagination.PageIndex" @changeSize="bookChangeSize"
              @changeCurrent="bookChangeCurrent">
            </pagination>
          </div>
        </div>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="staffDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addWaybill,
    putWaybill,
  } from '@/api/waybill'
  import {
    getAddress
  } from '@/api/address'
  import {
    getUser
  } from '@/api/user'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import waybillForm from '@/components/waybillForm'
  import forms from '@/components/forms'
  import {
    formRules,
    addressBook,
  } from "../views/OrderManagement/uncertain.js";
  export default {
    name: 'addEditOrder',
    components: {
      tables,
      pagination,
      waybillForm,
      forms,
    },
    props: {
      staffTitle: {
        type: String,
        default: () => '添加',
      },
      operationType: {
        type: String,
        default: () => 'add',
      },
      orderInformation: {
        type: Object,
        default: () => {},
      },
      orderId: {
        type: Number,
        default: () => null,
      },
    },
    data() {
      return {
        staffDialogVisible: false,
        recipientsForm: {
          name: '',
          phone: '',
          region: '',
          address: '',
        },
        conserveFlag: true,
        saveConsigneeAddress: true,
        delivererName: '',
        ruleForm: {
          deliveryType: '现在配送',
          askForTime: null,
          is_secondary_distribution: false,
          tamperProofLabel: '',
          tamperProofLabelImg: '',
          remark: '',
          fileList: [],
          drugCode: [],
        },
        formRuleList: [],
        conserveFlag: true,
        saveConsigneeAddress: true,
        innerVisible: false,
        bookInput: '',
        bookTableList: [],
        bookTableData: [],
        bookType: '',
        bookPagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        bookTotal: 0,
        confirmLoading: false,

      }
    },
    watch: {
      orderInformation: {
        handler(newVal, oldVal) {
          // console.log(newVal, 'val')
          setTimeout(() => {
            this.$nextTick(() => {
              if (newVal.id) {
                this.recipientsForm.name = newVal.consigneeAddressName
                this.recipientsForm.phone = newVal.consigneeAddressPhone
                this.recipientsForm.address = newVal.consigneeAddressDetails
                this.ruleForm.tamperProofLabel = newVal.tamperProofLabel
                this.ruleForm.drugCode = newVal.drugs
                if (newVal.deliveryType) {
                  this.ruleForm.deliveryType = newVal.deliveryType
                }
                if (newVal.askForTime) {
                  this.ruleForm.askForTime = newVal.askForTime
                }
                this.ruleForm.is_secondary_distribution = newVal.is_secondary_distribution
                if (newVal.tamperProofLabelImg) {
                  var arr = newVal.tamperProofLabelImg.split(',')
                  var arr3 = []
                  arr.forEach((item, index) => {
                    var arr1 = {
                      url: '',
                    }
                    arr1.url = item
                    arr3.push(arr1)
                  })
                  this.ruleForm.fileList = arr3
                  this.ruleForm.tamperProofLabelImg = newVal.tamperProofLabelImg
                }
                if (newVal.drugs && newVal.drugs.length > 0) {
                  this.$refs.childRules.commodityList = newVal.drugs
                }
                this.ruleForm.remark = newVal.remark
              }
            })
          })
        },
        immediate: true,
        deep: true
      }
    },
    mounted() {
      const dataList = formRules();
      this.formRuleList = dataList;
    },
    methods: {
      // 弹窗表单添加
      async handleAdd() {
        let recipientsFlag = this.$refs['recipients'].validateForm();
        let childRulesFlag = this.$refs['childRules'].validateForm();
        if (recipientsFlag && childRulesFlag) {
          // if (this.ruleForm.drugCode.length > 0) {
          this.confirmLoading = true
          var params = {
            consigneeAddressName: this.recipientsForm.name,
            consigneeAddressPhone: this.recipientsForm.phone,
            consigneeAddressDetails: this.recipientsForm.address,
            saveConsigneeAddress: this.saveConsigneeAddress,
            // deliveryId: Number(this.personnelForm.deliveryId),
            // reCheckId: Number(this.personnelForm.reCheckId),
            ...this.ruleForm,
            drugs: this.ruleForm.drugCode
          }
          if (this.ruleForm.fileList) {
            var fileImage = this.picture(this.ruleForm.fileList)
            params.tamperProofLabelImg = fileImage
          }
          if (!params.askForTime) {
            delete params.askForTime
          }
          if (this.operationType == 'add') {
            delete params.fileList
            delete params.drugCode
            delete params.code
            await addWaybill(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                // this.getList()
                this.$emit('refreshList')
              }
              this.staffDialogVisible = false
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
          } else if (this.operationType == 'edit') {
            delete params.fileList
            delete params.drugCode
            delete params.code
            params.id = this.orderId
            await putWaybill(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                // this.getList()
                this.$emit('refreshList')
              }
              this.staffDialogVisible = false
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
          }
          // } else {
          //   this.$message.error('请扫码添加商品');
          // }
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      picture(arr) {
        var imgList = JSON.parse(JSON.stringify(arr))
        var imgArr = []
        imgList.forEach((item, index) => {
          imgArr.push(item.url)
        })
        var imgString = imgArr.join()
        return imgString
      },
      // 获取地址簿
      getAddressBook(type) {
        this.bookTableList = addressBook()
        this.bookType = type
        this.innerVisible = true
        this.getSenderSend()
      },
      conserveSelectil(type) {
        if (type) {
          this.saveConsigneeAddress = true
        } else {
          this.saveConsigneeAddress = false
        }
      },
      // 快速搜索
      fastSearch() {
        this.bookPagination.PageIndex = 1
        if (this.bookType == 'deliverer') {
          this.getDelivererList()
        }
      },
      // 获取寄/收列表
      getSenderSend() {
        let address = ''
        if (this.bookType == 'recipients') {
          address = 'consignee'
        } else {
          address = this.bookType
        }
        getAddress({
          page: this.bookPagination.PageIndex,
          pageSize: this.bookPagination.PageSize,
          name: this.bookInput,
          addressType: address,
        }).then(res => {
          if (res.code == 200) {
            this.bookTableData = res.data.list
            this.bookTotal = res.data.count
          }
        })
      },
      getDelivererList() {
        var params = {
          page: 1,
          pageSize: 999,
          // type: 3,
          name: this.delivererName,
        }
        getUser(params).then(res => {
          if (res.code == 200) {
            let arr = res.data.list
            let arrList = []
            arr.forEach(item1 => {
              var arrData = {
                label: null,
                value: null,
              }
              arrData.label = item1.nickName
              arrData.value = item1.id
              arrList.push(arrData)
            })
            this.personnelList.forEach(item => {
              if (item.field == 'deliveryId') {
                item.options = item.options.concat(arrList)
              }
            })
          }
        })
      },
      // 地址簿
      bookChangeSize(val) {
        this.bookPagination.PageSize = val
        if (this.bookType == 'deliverer') {
          this.getDelivererList()
        } else {
          this.getSenderSend()
        }
      },
      bookChangeCurrent(val) {
        this.bookPagination.PageIndex = val
        if (this.bookType == 'deliverer') {
          this.getDelivererList()
        } else {
          this.getSenderSend()
        }
      },
      // 选择table其中某一项
      cellClick(row) {
        this.innerVisible = false
        const param = {
          ...row
        }
        if (this.bookType == 'recipients') {
          this.recipientsForm = param
          this.$nextTick(() => {
            this.$refs.recipients.radio = ''
            // this.$refs['recipients'].clickitem('1')
            this.$refs['recipients'].validateForm();
          })
        } else if (this.bookType == 'deliverer') {
          this.delivererForm.name = param.nickName
          this.delivererForm.phone = param.phone
          this.$nextTick(() => {
            this.$refs['deliverer'].validateForm();
          })
        }
      },
      // 关闭清空表单
      closePopup() {
        this.ruleForm.fileList = []
        this.$refs.childRules.commodityList = []
        // this.$refs.sender.resetForm()
        this.$refs.recipients.resetForm()
        // this.$refs.deliverer.resetForm()
        this.$refs.childRules.resetCheck()
      }
    }
  }
</script>

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