<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="维修报价"
    width="700px"
    @cancel="clearInfo"
    :confirmLoading="loading"
    @ok="handleSubmit"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
        <template #add>
          <div>
            <!-- <Button  @click="add" style="margin-left:20px">添加人工</Button> -->
            <Button  @click="updataRepairInfo">重置</Button>
          </div>
        </template> 
        <template #del="{ field }">
          <Button @click="del(field)">删除</Button>
        </template>
        <template #delList="{ field }">
          <Button @click="del(field)">删除</Button>
        </template>
      </BasicForm>
      <div class="priceCount">
        <span>合计：</span>
        <div class="label">总价：{{ fileFlow.priceCount || 0 }}元 <Button :preIcon="'outline-refresh'"  @click="updataCount"><RedoOutlined /></Button></div>
        <p style="padding-top:15px">注：提交报价后，需等待报修人确认后再进行维修</p>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, h, onMounted, reactive, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getPriceList, checkRegisterInfo, addOrUpdatePriceList, allList } from '/@/api/spares'
  import { Checkbox, Button } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { uploadApi } from '/@/api/product/index';
  import { RedoOutlined, } from '@ant-design/icons-vue';
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm, RedoOutlined, Checkbox, Button },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const n = ref(1);
      const fileFlow = reactive({
        file:null,
        type:2,//2-普通发票，3-专用发票
        count:1,//第一次报价
        priceCount:0,//总价
        priceLists:[],
        priceListsPrice:{},
        manMadeList:[],
      })
      const loading = ref(false)
      const { createMessage,createConfirm } = useMessage();
      const schemas: FormSchema[] = [
          {
            field: 'id',
            component: 'Input',
            show:false,
            label: '发票编号',
          },
          {
            field: 'repairId',
            component: 'Input',
            label: '维修单号',
            slot: 'text',
            colProps: {
              span: 24,
            },
          },{
            field: 'deviceInfo',
            component: 'Input',
            label: '设备信息',
            slot: 'text',
            colProps: {
              span: 18,
            },
          },{
            field: 'warrantyExpirationDateText',
            component: 'Input',
            slot: 'text',
            label: '保修届满日期',
          },{
            field: 'checkResult',
            component: 'Input',
            label: '检测结果',
            slot: 'text',
            colProps: {
              span: 18,
            },
          },{
            field: '0',
            component: 'Input',
            label: '报价明细',
            labelWidth:0,
            colProps: {
              span: 24,
            },
            slot: 'add',
          },{
            field: 'manMade',
            component: 'CheckboxGroup',
            label: '人工费',
            labelWidth:0,
            componentProps: {
              options: fileFlow.manMadeList,
              maxLength: 50,
              onChange:(val)=>{
                setTimeout(() => {
                updataCount()
              }, 100)
              },
            },
            colProps: {
              span: 24,
            },
          },
      ];

      const [registerForm, { validate, getFieldsValue, resetFields, setFieldsValue, removeSchemaByFiled, appendSchemaByField, updateSchema }] = useForm({
        labelWidth: 100,
        labelAlign:'left',
        schemas:schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(async () => {
        let allListOption = await allList()//获取价格
        console.log('allList',allListOption)
        fileFlow.priceListsPrice
        allListOption.map(ele => {
          fileFlow.manMadeList.push({
            ...ele,
            label: `${ele.name} ${ele.price}元`,
            value: ele.laborCostId,
          })
          fileFlow.priceListsPrice[ele.laborCostId] = ele.price
        })
      });
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      async function updataRepairInfo() {
        let { repairId } = getFieldsValue()
        console.log('20230228171427939',repairId)
        const { priceLists, count } = await getPriceList({repairId})//
        addPriceItem(priceLists)
        clearInfo(true)
        setTimeout(() => {
          updataCount()
        }, 100);
      }
      async function onDataReceive(data) {

        const { priceLists, count } = await getPriceList({repairId:data.repairId})//
        addPriceItem(priceLists)
        resetFields();
        fileFlow.type = data.type
        setFieldsValue({
          ...data,
          warrantyExpirationDateText: `${data.warrantyDate} (${data.warrantyType==0?'保内维修':data.warrantyType==1?'保内转保外':'保外维修'})`,
          deviceInfo:t(`routes.scene.tableType.${data.cameraType}`)+data.cameraSnCode
        });
      }
      function del(field) {
        removeSchemaByFiled([`deviceType${field}`, `device_${field}`, `${field}`]);
        // n.value--;
      }
      function add() {
        let list = addSchemas(n.value);
        list.map(ele => {
          appendSchemaByField(ele,'')
        })
        n.value++
      }
      function addPriceItem(list){
        fileFlow.priceLists = list
        let priceSchema = [],valueObj = {},count=0
        let manMade = [],countIndex = 0
        console.log('addPriceItem',fileFlow.priceLists)
        fileFlow.priceLists.map((ele,index) => {
          if(ele.type == 1){//人工费
            manMade.push(ele.partId)
            count = count + ele.count*ele.price
          }else{//备件
          countIndex++
          let price = ele.discount == 1?ele.priceDiscount:ele.price
          valueObj[`priceList${ele.priceListId}`] = ele.count || 0
          valueObj[`priceListText${ele.priceListId}`] = `${ele.name} ${ele.price} 元/${ele.partUnit}`
          valueObj[`discount${ele.priceListId}`] = ele.discount == 1?[0]:[]
          count = count + ele.count*price
          priceSchema.push({
          // priceSchema.unshift({
            field: 'priceListText' + ele.priceListId,
            component: 'InputNumber',
            label: countIndex,
            labelWidth:20,
            slot: 'text',
            // labelWidth:300,
            // subLabel:"数量",
            colProps: {
              span: Boolean(ele.priceDiscount)?8:16,
            }
          },{
            field: 'discount' + ele.priceListId,
            component: 'CheckboxGroup',
            ifShow:Boolean(ele.priceDiscount),
            componentProps: {
              onChange:(val)=>{
                setTimeout(() => {
                updataCount()
              }, 100)
              },
              options: [
              {
                label: `折扣价 ${ele.priceDiscount}元`,
                value: 0,
              },
            ]
            },
            colProps: {
              span: 8,
            }
          },{
            field: 'priceList' + ele.priceListId,
            label: '数量',//`${ele.type == 0?'备件':'人工'}：  ${ele.name} ${ele.price} 元/次`,
            // suffix:'数量',
            component: 'InputNumber',
            defaultValue:ele.count || 0,
            labelWidth:50,
            // labelWidth:300,
            // subLabel:"数量",
            colProps: {
              span: 8,
            },
            required: true,
            componentProps: {
              disabled:ele.status == 1,
              min:0,
              max:999,
              maxLength: 15,
              onChange:(val)=>{
                setTimeout(() => {
                updataCount()
              }, 100)
              }
            },
          })
          }
        })
        fileFlow.priceCount = count.toFixed(2)
        valueObj.manMade = manMade
        priceSchema.map(item =>{
          console.log('priceSchema',item)
          appendSchemaByField(item,'')
        })
        console.log('addPriceItem',valueObj)
        setTimeout(()=>{
          setFieldsValue(valueObj)
        },10)
      }
      function addSchemas(number){
        let parentList: FormSchema[] = [
          {
            field: 'deviceType' + number,
            label: '人工',
            component: 'ApiSelect',
            colProps: {
              span: 12,
            },
            required: true,
            componentProps: {
              api: allList,
              labelField: 'name',
              valueField: 'laborCostId',
              showSearch:true,
              onChange:(value)=>{
                console.log('onchange',value,arguments)
              }
            },
          },
          {
            field: 'device_' + number,
            label: '数量',
            component: 'InputNumber',
            required: true,
            defaultValue: 1,
            labelWidth:50,
            componentProps: {
              max: 999,
              min:1,
            },
            colProps: {
              span: 6,
            },
          },{
            field: number.toString(),
            component: 'Input',
            label: '',
            labelWidth:0,
            colProps: {
              span: 6,
            },
            slot: 'del',
          }
        ];
        return parentList
      }
      const handleSubmit = async () => {
        const params = await validate(); 
        try {
          createConfirm({
          iconType: 'warning',
          title: () => h('span', '温馨提示'),
          content: '确定要提交报价吗?',
          onOk: async () => {
            loading.value = true
            let priceListsparams = []
            console.log('params',n.value,fileFlow.priceLists) 
            fileFlow.priceLists.map(ele => {
              if(ele.type == 1){
                return
              }
              let discount = params[`discount${ele.priceListId}`]?.length?1:0;
            console.log('discount',discount) 
              priceListsparams.push({
                priceListId:ele.priceListId,
                type:ele.type,
                laborId:ele.laborId,
                partId:ele.partId,
                discount,
                count:params[`priceList${ele.priceListId}`],
              })
            })
            let manMade = params.manMade
            fileFlow.manMadeList.map(ele => {
              if(manMade.includes(ele.laborCostId)){
                priceListsparams.push({
                  count:1,
                  priceListId:ele.priceListId,
                  laborId:ele.laborCostId,
                  partId:ele.laborCostId,
                  type:1,
                })
              }
            })
            let res = await addOrUpdatePriceList({
              repairId:params.repairId,
              priceLists:priceListsparams,
            })
            console.log('res',res)
            createMessage.success(t('common.optSuccess'));
            closeModal();
            emit('update');
            loading.value = false
            clearInfo()
          },
          onCancel: () => {
            loading.value = false
          }
        });
        } catch (error) {
          loading.value = false
          console.log('not passing', error);
        }
      };
      function updataCount(){
        let fromData = getFieldsValue() ,count = 0
        // fileFlow.priceListsPrice
        console.log('fromData',fromData,fileFlow.priceLists)
        fileFlow.priceLists.map(ele => {
          let price = Number(fromData[`discount${ele.priceListId}`]?.length?ele.priceDiscount:ele.price);
          console.log('count',price, count)
          if(fromData[`priceList${ele.priceListId}`]){
            count = count + fromData[`priceList${ele.priceListId}`]*price
          }
        })
        let manMade = fromData.manMade
        fileFlow.manMadeList.map(ele => {
          if(manMade?.includes(ele.laborCostId)){
            count = count + Number(ele.price)
          }
        })
        for (let index = 1; index < n.value; index++) {
          if(fromData[`deviceType${index}`] && fromData[`device_${index}`]){
            let priceId = fromData[`deviceType${index}`]
            let fromPrice = fromData[`device_${index}`] * fileFlow.priceListsPrice[priceId]
            count = count +fromPrice
          }
        }
        fileFlow.priceCount = count.toFixed(2)
      }

      function clearInfo(val){
        let indexa = n.value;
        fileFlow.priceCount = 0
        if(!val){
          resetFields()
        }
        let clearFiled = []
        fileFlow.priceLists.map(ele =>{
          clearFiled.push(`priceList${ele.priceListId}`,`priceListText${ele.priceListId}`,`discount${ele.priceListId}`)
        })
        for (let index = 1; index < indexa; index++) {
          clearFiled.push(`deviceType${index}`, `device_${index}`, `${index}`)
        }
        removeSchemaByFiled(clearFiled);
        n.value = 1
      }

      return {
        register,
        registerForm,
        fileFlow,
        handleSubmit,
        addListFunc,
        resetFields,
        loading,
        clearInfo,
        updataCount,
        t,
        del,
        add,
        updataRepairInfo,
      };
    },
  });
</script>

<style lang="less" scoped>
.priceCount{
  // padding: 20px 180px;
  line-height: 32px;
  .label{
    display: inline-block;
  }
}
</style>
