<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" style="margin-left:20px">重置</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>
      </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 { 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 },
    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:{}
      })
      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: 'checkResult',
            component: 'Input',
            label: '检测结果',
            slot: 'text',
            colProps: {
              span: 18,
            },
          },{
            field: '0',
            component: 'Input',
            label: '报价明细',
            labelWidth:0,
            colProps: {
              span: 24,
            },
            slot: 'add',
          },
      ];

      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.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,
          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.reverse()
        let priceSchema = [],valueObj = {},count=0
        list.map(ele => {
          valueObj[`priceList${ele.priceListId}`] = ele.count || 0
          valueObj[`priceListText${ele.priceListId}`] = `${ele.name} ${ele.price} 元/次`
          count = count + ele.count*ele.price
          priceSchema.unshift({
            field: 'priceListText' + ele.priceListId,
            component: 'InputNumber',
            label: ele.type == 0?'备件':'人工',
            slot: 'text',
            // labelWidth:300,
            // subLabel:"数量",
            colProps: {
              span: 12,
            }
          },{
            field: 'priceList' + ele.priceListId,
            label: '数量',//`${ele.type == 0?'备件':'人工'}：  ${ele.name} ${ele.price} 元/次`,
            // suffix:'数量',
            component: 'InputNumber',
            defaultValue:ele.count || 0,
            // labelWidth:300,
            // subLabel:"数量",
            colProps: {
              span: 12,
            },
            required: true,
            componentProps: {
              disabled:ele.status == 1,
              min:0,
              max:999,
              maxLength: 15,
              onChange:(val)=>{
                setTimeout(() => {
                updataCount()
              }, 100)
              }
            },
          })
        })
        fileFlow.priceCount = count
        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('addOrUpdatePriceList',params,fileFlow.priceLists) 
            fileFlow.priceLists.map(ele => {
              priceListsparams.push({
                type:ele.type,
                laborId:ele.laborId,
                partId:ele.partId,
                count:params[`priceList${ele.priceListId}`]
              })
            })
            for (let index = 1; index < n.value; index++) {
              if(params[`device_${index}`]){
                priceListsparams.push({
                  // priceListId:params[`deviceType${index}`],
                  count:params[`device_${index}`],
                  laborId:params[`deviceType${index}`],
                  partId:params[`deviceType${index}`],
                  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.map(ele => {
          count = count + fromData[`priceList${ele.priceListId}`]*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
      }

      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}`)
        })
        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;
  .label{
    display: inline-block;
  }
}
</style>
